Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# SortNoAlloc for List, Array, etc...
using System.Collections.Generic;
public static class ContainerExtensions
{
public static void SortNoAlloc<T>(this IList<T> list) where T : System.IComparable<T>
{
if(list.Count <= 1) return;
QuickSort(list, 0, list.Count - 1);
}
private static int Partition<T>(IList<T> list, int low, int high) where T : System.IComparable<T>
{
T pivot = list[high];
int i = (low - 1);
for(int j = low; j < high; j++)
{
if(list[j].CompareTo(pivot) <= 0)
{
i++;
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
T otherTemp = list[i + 1];
list[i + 1] = list[high];
list[high] = otherTemp;
return i + 1;
}
private static void QuickSort<T>(IList<T> list, int low, int high) where T : System.IComparable<T>
{
if(low < high)
{
int partitionIndex = Partition<T>(list, low, high);
QuickSort(list, low, partitionIndex - 1);
QuickSort(list, partitionIndex + 1, high);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment