Skip to content

Instantly share code, notes, and snippets.

@HighTeaFrog
Created January 25, 2019 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HighTeaFrog/3fd4d2589fa71161dbe6b34321f44219 to your computer and use it in GitHub Desktop.
Save HighTeaFrog/3fd4d2589fa71161dbe6b34321f44219 to your computer and use it in GitHub Desktop.
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