Skip to content

Instantly share code, notes, and snippets.

@christiannagel
Created July 22, 2017 07:45
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 christiannagel/83f273ca0c15d8823fb35670331fa58d to your computer and use it in GitHub Desktop.
Save christiannagel/83f273ca0c15d8823fb35670331fa58d to your computer and use it in GitHub Desktop.
Quicksort with recursive local function
public static void QuickSort<T>(T[] elements) where T : IComparable<T>
{
void Sort(int start, int end)
{
int i = start, j = end;
var pivot = elements[(start + end) / 2];
while (i <= j)
{
while (elements[i].CompareTo(pivot) < 0) i++;
while (elements[j].CompareTo(pivot) > 0) j--;
if (i <= j)
{
T tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
i++;
j--;
}
}
if (start < j) Sort(start, j);
if (i < end) Sort(i, end);
}
Sort(0, elements.Length - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment