Skip to content

Instantly share code, notes, and snippets.

@nilpunch
Last active June 30, 2025 07:15
Show Gist options
  • Select an option

  • Save nilpunch/ede2aab86395edfa1799ed61b9796ce1 to your computer and use it in GitHub Desktop.

Select an option

Save nilpunch/ede2aab86395edfa1799ed61b9796ce1 to your computer and use it in GitHub Desktop.
C# Radix
public static class ListExtensions
{
public static void RadixSort<T>(this List<T> list, Func<T, uint> orderBy)
{
RadixCountBytesSort(list, orderBy);
}
private static void RadixCountBytesSort<T>(List<T> list, Func<T, uint> orderOf)
{
var count = list.Count;
var keys = ArrayPool<uint>.Shared.Rent(count);
var buffer = ArrayPool<T>.Shared.Rent(count);
for (var i = 0; i < count; i++)
keys[i] = orderOf(list[i]);
for (var shift = 0; shift < 32; shift += 8)
{
CountSort8Bits(list, buffer, keys, shift);
}
ArrayPool<uint>.Shared.Return(keys);
ArrayPool<T>.Shared.Return(buffer, clearArray: true);
}
private static void CountSort8Bits<T>(List<T> input, T[] buffer, uint[] keys, int shift)
{
var count = input.Count;
var buckets = ArrayPool<int>.Shared.Rent(256);
for (var i = 0; i < count; i++)
buckets[(keys[i] >> shift) & 0xFF]++;
for (var i = 1; i < 256; i++)
buckets[i] += buckets[i - 1];
for (var i = count - 1; i >= 0; i--)
{
var bucket = (keys[i] >> shift) & 0xFF;
var pos = --buckets[bucket];
buffer[pos] = input[i];
}
for (var i = 0; i < count; i++)
input[i] = buffer[i];
ArrayPool<int>.Shared.Return(buckets);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment