Quick sort picks one element as a pivot, moves everything smaller to its left and everything larger to its right, then repeats the process on each side. Tony Hoare published it in 1961, and it is still the core of most general-purpose sorting routines, including the one behind Array.Sort in .NET.
The version below is written for current .NET. It sorts any T that implements IComparable<T>, works on arrays and Span<T> alike, and fixes two problems that the textbook version leaves open.
Usage
int[] numbers = { 1, 5, 4, 11, 20, 8, 2, 98, 90, 16 };
QuickSort.Sort(numbers);
Console.WriteLine(string.Join(", ", numbers));
// 1, 2, 4, 5, 8, 11, 16, 20, 90, 98
Because the method is generic, the same call works for string[], DateTime[] or your own types, as long as they implement IComparable<T>.
Implementation
public static class QuickSort
{
public static void Sort<T>(T[] items) where T : IComparable<T>
=> Sort(items.AsSpan());
public static void Sort<T>(Span<T> items) where T : IComparable<T>
{
while (items.Length > 1)
{
int p = Partition(items);
// Recurse into the smaller part and loop over the larger one.
// This keeps the call stack at O(log n) even on bad input.
if (p < items.Length - p - 1)
{
Sort(items[..p]);
items = items[(p + 1)..];
}
else
{
Sort(items[(p + 1)..]);
items = items[..p];
}
}
}
private static int Partition<T>(Span<T> items) where T : IComparable<T>
{
int mid = items.Length / 2;
int last = items.Length - 1;
// Median of three: put the median of first, middle and last
// at the end and use it as the pivot.
if (items[mid].CompareTo(items[0]) < 0) Swap(items, mid, 0);
if (items[last].CompareTo(items[0]) < 0) Swap(items, last, 0);
if (items[mid].CompareTo(items[last]) < 0) Swap(items, mid, last);
T pivot = items[last];
int i = -1;
for (int j = 0; j < last; j++)
{
if (items[j].CompareTo(pivot) <= 0)
{
i++;
Swap(items, i, j);
}
}
Swap(items, i + 1, last);
return i + 1;
}
private static void Swap<T>(Span<T> items, int a, int b)
=> (items[a], items[b]) = (items[b], items[a]);
}
What changed from the textbook version
Pivot choice. The classic example always uses the last element as the pivot. Feed it an array that is already sorted and every partition splits off a single element, so the run time drops to O(n²). Taking the median of the first, middle and last elements makes that case behave like an average one.
Stack depth. A naive recursive quick sort can go n levels deep on unlucky input, which is enough to crash a process with a StackOverflowException on large arrays. Recursing only into the smaller partition and looping over the larger one caps the depth at about log₂ n.
Spans instead of index pairs. Passing Span<T> slices instead of start and end indexes removes a whole class of off-by-one mistakes, and it lets you sort part of an array without copying it: QuickSort.Sort(numbers.AsSpan(2, 5)).
Complexity
| Case | Time | Extra space |
|---|---|---|
| Average | O(n log n) | O(log n) |
| Worst | O(n²) | O(log n) |
Quick sort is not stable: two equal elements may end up in a different order than they started in. If that matters, sort with LINQ’s OrderBy, which is stable.
Should you use this in production?
Usually not. Array.Sort and Span<T>.Sort use introsort, a hybrid of quick sort, heap sort and insertion sort that guards against the worst case and is heavily optimised. Write your own when you are learning the algorithm, preparing for an interview, or need to change how partitioning works. One known weakness of the version above: an input made almost entirely of equal values still degrades, because this partition scheme does not group duplicates together.
Isn’t it default Call by Value in C#? so how does the array have the right values in the end?
Arrays in .NET are object on the heap, so you have a reference. That reference is passed by value, meaning that changes to the contents of the array will be seen by the caller, but reassigning the array won’t: