Created
January 25, 2019 13:58
-
-
Save HighTeaFrog/3fd4d2589fa71161dbe6b34321f44219 to your computer and use it in GitHub Desktop.
C# SortNoAlloc for List, Array, etc...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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