Quicksort
Pick a pivot, partition the array into smaller and larger values around it, then sort each side the same way: O(n log n) on average, in place.
Description
Quicksort is a divide-and-conquer sort. It picks one element as the pivot, then partitions the array so that everything smaller than the pivot comes before it and everything larger after it. The pivot is now in its final position. Quicksort then sorts the left and right parts the same way, recursively.
The partition step does the real work. In the Lomuto scheme shown below, the last element is the pivot; a pointer i marks the end of the "smaller" region, and a second pointer j scans the array, swapping each smaller value into that region. The Hoare scheme uses two pointers moving towards each other and does fewer swaps.
On average each partition splits the array roughly in half, giving about log₂ n levels of n work each: O(n log n). But if the pivot is always the smallest or largest value, for example taking the last element of an already sorted array, every split is lopsided and quicksort degrades to O(n²). Choosing a random pivot, or the median of three, makes that very unlikely.
Quicksort sorts in place with little extra memory and has excellent cache behavior, which is why it's often the fastest general-purpose sort in practice. It isn't stable: equal values can change order.
How it works
One partition: pivot 55; values smaller than 55 move to the left
- index 0: 38
- index 1: 27
- index 2: 43
- index 3: 3
- index 4: 9
- index 5: 10
- index 6: 55
- index 7: 82
Step through: quicksort with the Lomuto partition
Step 1 of 34Start with 8 values.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Sort (average)With random or median-of-three pivots, the worst case is very unlikely. | O(n log n) | O(n log n) |
| Sort (worst case)Lopsided pivots, such as the last element of sorted input. | O(n²) | O(n²) |
| Best caseEvery pivot splits the array in half. | O(n log n) | O(n log n) |
Space: O(log n) for the recursion stack (O(n) in the worst case)
Quicksort is not stable. Many standard libraries use introsort, which starts as quicksort and switches to heapsort if recursion gets too deep, guaranteeing O(n log n) in the worst case.
TypeScript implementation
In-place quicksort with a random pivot and the Lomuto partition scheme.
// In-place quicksort with a random pivot and the Lomuto partition scheme.
export function quicksort(a: number[], lo = 0, hi = a.length - 1, random: () => number = Math.random): number[] {
if (lo >= hi) return a;
const p = partition(a, lo, hi, random);
quicksort(a, lo, p - 1, random);
quicksort(a, p + 1, hi, random);
return a;
}
/** Puts a[hi]'s value in its final place p, with smaller values before it. Returns p. */
function partition(a: number[], lo: number, hi: number, random: () => number): number {
// A random pivot makes the O(n²) worst case very unlikely, even on sorted input.
const r = lo + Math.floor(random() * (hi - lo + 1));
[a[r], a[hi]] = [a[hi], a[r]];
const pivot = a[hi];
let i = lo; // a[lo..i-1] holds values smaller than the pivot
for (let j = lo; j < hi; j++) {
if (a[j] < pivot) {
[a[i], a[j]] = [a[j], a[i]];
i++;
}
}
[a[i], a[hi]] = [a[hi], a[i]]; // the pivot lands between the two parts
return i;
}
export function demo(): string[] {
let seed = 7;
const random = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); // repeatable for the demo
const lines = [`[38, 27, 43, 3, 9, 82, 10, 55] → [${quicksort([38, 27, 43, 3, 9, 82, 10, 55], 0, 7, random).join(", ")}]`];
// Sorted input is the classic worst case for a fixed last-element pivot; a random pivot handles it.
const sorted = Array.from({ length: 10_000 }, (_, i) => i);
const t0 = performance.now();
quicksort([...sorted], 0, sorted.length - 1, random);
lines.push(`10 000 already-sorted values: ${(performance.now() - t0).toFixed(1)} ms with a random pivot`);
const withDupes = [5, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
lines.push(`with duplicates → [${quicksort(withDupes, 0, withDupes.length - 1, random).join(", ")}]`);
return lines;
}When to use it
Use it when
- You need a fast, general-purpose, in-place sort for arrays in memory.
- Stability doesn't matter, such as sorting numbers or unique keys.
- As the basis for quickselect: finding the k-th smallest value in O(n) on average.
Avoid it when
- You need a stable sort, such as sorting records by one field and then another: use merge sort or Timsort.
- You need a guaranteed O(n log n) worst case without randomization: use heapsort or merge sort.
- The data is a linked list, or doesn't fit in memory: merge sort is a better fit.
Pitfalls
- Always choosing the first or last element as pivot, which makes sorted or reversed input quadratic.
- Many duplicate values with a two-way partition, which also degrades towards O(n²). Use three-way partitioning (Dutch national flag).
- Deep recursion on bad inputs, which can overflow the stack. Recurse on the smaller side and loop on the larger one.
- Off-by-one errors in partition bounds, the most common source of infinite loops in hand-written quicksort.
Alternatives
Merge sort
Choose it when you need stability, a guaranteed O(n log n), or to sort linked lists or data on disk.
Heapsort
Choose it when you need in-place sorting with a guaranteed O(n log n) worst case.
Insertion sort
Choose it when the array is tiny or nearly sorted. Quicksort implementations often switch to it for small partitions.
Timsort
Choose it when you're using your language's built-in sort. It's stable and very fast on real-world data.