Quicksort in Depth
Expected 2n ln n comparisons, pivot rules, duplicate keys and introsort.
Quicksort is more than sixty years old and still sits at the core of the fastest general-purpose sorts, yet it is quadratic in the worst case, and in 1999 Doug McIlroy wrote a short function that drives almost any deterministic quicksort into that worst case on demand. Its success rests on a precise average of comparisons, a tight concentration around it, and decades of engineering: better pivots, three-way partitions, two pivots, and fallbacks that cap the worst case.
What you’ll learn
- Solve the quicksort recurrence exactly, , and describe how concentrated is: its variance, its limit law and its tails.
- Quantify pivot sampling (median of 3 lowers to ) and explain why every deterministic pivot rule has an adversary.
- Handle repeated keys with Hoare's partition or three-way partitioning, and relate the cost to the entropy lower bound.
- Explain what dual-pivot quicksort, introsort and pattern-defeating quicksort change: comparisons, memory traffic, branch mispredictions and the worst case.
The exact expected cost, and its spread
With a uniformly random pivot, the pivot's rank is uniform on , partitioning costs comparisons, and the two sides are independent random instances of sizes and . The Optimized lesson proved the mean with indicator variables; the recurrence gives it too, and it is the route to the variance.
Recurrence. Write with . Averaging over the pivot's rank, both sides range over the same sizes:
Remove the sum. Multiply by , and subtract the same identity for :
Telescope. Divide by ; the left side becomes a difference of consecutive terms:
Close the sum. , so the sum is . Checked in exact rational arithmetic for every :
A weaker statement has a five-line proof. Follow one key . A partition round is good for if the pivot of 's range has a rank in the middle half, which happens with probability at least , independently of earlier rounds, and then 's range shrinks to at most of its size. After good rounds, is alone. A Chernoff bound makes fewer than that many good rounds among the first rounds unlikely, with probability at most for a suitable constant . The key is compared once per round, so a union bound over the keys gives with high probability, at least .
For large , how many times the counting bound does randomized quicksort spend on average? Give the limit of .
Show the answer
1.39
and , so the ratio tends to : about 39% above the minimum. Median-of-three pivots cut the excess to about 19%. The limit is approached slowly, since the term matters for any practical .
Pivot sampling, and adversaries
A better pivot splits more evenly. Taking the median of a small random sample as the pivot lowers the constant, at the price of the comparisons that find the median. For a sample of keys, the expected count is to first order, which tends to the counting bound as the sample grows:
| Pivot | Coefficient of | Coefficient of |
|---|---|---|
| random key | 2 | 1.386 |
| median of 3 | 1.188 | |
| median of 5 | 1.622 | 1.124 |
| median of 7 | 1.576 | 1.092 |
| median of 21 | 1.490 | 1.033 |
qsort (1993) uses the median of 3 on mid-sized ranges and Tukey's ninther, the median of three medians of three, on large ones.def make_killer(n):
"""McIlroy's adversary: a key's value is decided only when the sort needs it."""
GAS = n # "gas" compares above every frozen value
val, frozen, candidate = [GAS] * n, [0], [None]
def freeze(x):
val[x] = frozen[0]; frozen[0] += 1
def less(x, y): # the sort sorts the indices 0..n-1 with this
if val[x] == GAS and val[y] == GAS: # two unknowns: freeze the likely pivot
freeze(x if x == candidate[0] else y) # as the smallest value so far
if val[x] == GAS:
candidate[0] = x
elif val[y] == GAS:
candidate[0] = y
return val[x] < val[y]
return val, lessRun against a median-of-three quicksort with Lomuto partitioning, like the widget's, on keys, this comparison function forces 251,000 comparisons (about ), against about 10,800 on random inputs; sorting the input it built, with ordinary comparisons, costs exactly 251,000 again. Random pivots defeat it, because the adversary cannot predict the coins.
Equal keys: three ways to partition
Real data repeats keys: status codes, ages, dates. The two classic partitions react very differently:
- Lomuto sends every key pivot to the left. With all keys equal, each partition peels off only the pivot, and the sort costs exactly comparisons.
- Hoare stops both scans at keys equal to the pivot and swaps them, so the scans meet near the middle: balanced splits and , at the price of swaps that achieve nothing.
- Three-way partitioning, Dijkstra's Dutch national flag scheme, splits the range in one pass into keys , and the pivot, and never touches the equal block again.
import random
def quicksort3(a, lo=0, hi=None):
"""Quicksort with a three-way partition: < pivot, == pivot, > pivot."""
if hi is None:
hi = len(a) - 1
while lo < hi:
pivot = a[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi # a[lo..lt-1] < pivot, a[lt..i-1] == pivot, a[gt+1..hi] > pivot
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]; lt += 1; i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]; gt -= 1
else:
i += 1
if lt - lo < hi - gt: # recurse on the smaller side, loop on the larger
quicksort3(a, lo, lt - 1); lo = gt + 1
else:
quicksort3(a, gt + 1, hi); hi = lt - 1The comment is the invariant; the keys in are not yet classified. Tested on thousands of random arrays with few and many distinct values.
| Input | Lomuto | Hoare | Three-way | Multinomial bound |
|---|---|---|---|---|
| 4,000 equal keys | 7,998,000 | about 55,000 | 8,000 | — |
| keys drawn from 10 values | about | about | about | about |
Why is quicksort with Lomuto's partition quadratic on equal keys, while Hoare's partition gives ?
- Lomuto compares every pair of keys twice
- Hoare's scans skip keys equal to the pivot without comparing them
- Lomuto puts every key pivot on one side, so each partition removes only the pivot, while Hoare's scans stop at equal keys from both ends and meet near the middle
- Lomuto's random pivot is not uniformly distributed
Show the answer
C. Lomuto puts every key pivot on one side, so each partition removes only the pivot, while Hoare's scans stop at equal keys from both ends and meet near the middle
With all keys equal, a[j] <= pivot is always true, so the left part receives everything and the right part nothing: sizes and 0, again and again. Hoare's scans stop at every equal key, swap, and advance, so they cross near the middle and the recursion stays balanced.
Sedgewick and Bentley conjectured that three-way quicksort is within a constant factor of the multinomial (entropy) lower bound, and Wild (2018) proved it for random multisets with copies of each value: median-of- three-way quicksort is asymptotically times the bound, the same constants as in the pivot-sampling table. Bentley and McIlroy's "fat partition" gets the three-way split from a Hoare-style scan by parking equal keys at both ends and swapping them to the middle at the end.
Hybrids: two pivots, a depth limit, and broken patterns
Two pivots. Yaroslavskiy's dual-pivot quicksort (2009) partitions around into three parts, and Java 7 adopted it in 2011 for sorting arrays of primitive types. Wild and Nebel (2012) computed its average exactly: comparisons and swaps, against comparisons and about swaps for classic quicksort with Hoare-style partitioning. Fewer comparisons and many more swaps, yet it is faster. Later analyses traced the speed to memory traffic: splitting three ways scans fewer elements in total, and on modern machines moving data costs more than comparing it. The best possible dual-pivot partitioning strategy needs about comparisons.
A depth limit. Introsort (Musser, 1997) runs quicksort but counts the recursion depth; past about levels it heapsorts the current range, and it finishes small ranges with insertion sort. Typical inputs never reach the limit, adversarial ones are capped at . It is the usual implementation of C++'s std::sort.
import heapq, math
def introsort(a):
def insertion(lo, hi): # finish small ranges
for j in range(lo + 1, hi + 1):
key, i = a[j], j - 1
while i >= lo and a[i] > key:
a[i + 1] = a[i]; i -= 1
a[i + 1] = key
def sort(lo, hi, depth):
while hi - lo > 16:
if depth == 0: # too many bad splits: heapsort this range
part = a[lo:hi + 1]; heapq.heapify(part)
a[lo:hi + 1] = [heapq.heappop(part) for _ in range(hi - lo + 1)]
return
depth -= 1
mid = lo + (hi - lo) // 2 # median of three, moved to a[hi]
m = sorted([(a[lo], lo), (a[mid], mid), (a[hi], hi)])[1][1]
a[m], a[hi] = a[hi], a[m]
p, i = a[hi], lo # Lomuto partition around a[hi]
for j in range(lo, hi):
if a[j] < p:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
sort(i + 1, hi, depth) # recurse on the right, loop on the left
hi = i - 1
insertion(lo, hi)
if a:
sort(0, len(a) - 1, 2 * int(math.log2(len(a))))A sketch, tested on random inputs with few and many distinct values. A real introsort heapsorts the range in place rather than through a copy, and partitions Hoare-style. Even on all-equal keys, where this Lomuto partition splits as badly as possible, the depth limit hands the range to heapsort and the time stays .
Key takeaways
- The quicksort recurrence telescopes to ; the standard deviation is only about , and with high probability.
- Pivot sampling lowers the constant: the median of 3 gives , and larger samples approach , but sampling only pays on large ranges.
- Every deterministic pivot rule has an adversary (McIlroy's gas trick forces about comparisons on a median-of-three quicksort); random pivots or a depth limit defend against it.
- Equal keys need Hoare's stop-on-equal scans or a three-way partition; three-way quicksort is linear on all-equal input and within a constant factor of the entropy bound on random multisets.
- Modern quicksorts are hybrids: dual pivots (Java), introsort's heapsort fallback (C++ libraries), and pdqsort's branch-free blocks and pattern breaking (Go).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Randomized quicksort sorts distinct keys, with about comparisons on average. Roughly how large is the standard deviation of the comparison count?
- About , near : under 3% of the mean
- About , about 20% of the mean
- About , near
- About , as large as the mean
Show the answer
A. About , near : under 3% of the mean
, so the standard deviation is about : about 2.6% of the mean. The mean grows like and the spread only like , so the relative spread shrinks as grows.
Choosing the pivot as the median of three random keys changes quicksort's expected comparisons, to first order, from to…
- , the counting bound
- nothing: one sample cannot change the constant
Show the answer
B.
For a sample of the constant is ; with that is . Larger samples approach , but only in the limit.
Why does introsort switch to heapsort once the recursion depth exceeds about ?
- Heapsort is faster than quicksort on random data
- Typical inputs never reach that depth, so quicksort's speed is kept, while any input that does is finished by heapsort, which caps the total at in the worst case
- To keep the sort stable
- Because median-of-three pivots fail on random inputs
Show the answer
B. Typical inputs never reach that depth, so quicksort's speed is kept, while any input that does is finished by heapsort, which caps the total at in the worst case
Balanced splits finish within about levels, so the limit is reached only after many bad splits. Each level of partitioning costs , the depth is capped at , and heapsort's on the leftover ranges keeps the total at .
Yaroslavskiy's dual-pivot quicksort makes about comparisons and swaps on average, against and for classic quicksort, yet it runs faster. What is the accepted explanation?
- Comparisons are the only cost that matters, and it makes 5% fewer
- Swaps are free on modern hardware
- It scans fewer elements in total, so less data moves through the memory hierarchy, which costs more than the extra swaps
- It is stable, so it avoids extra work on equal keys
Show the answer
C. It scans fewer elements in total, so less data moves through the memory hierarchy, which costs more than the extra swaps
Splitting into three parts per pass means fewer passes over the data. Analyses that count scanned elements, a proxy for memory traffic and cache misses, show dual-pivot quicksort ahead, matching the measurements; counting comparisons and swaps alone predicts the opposite.
Further reading
- C. A. R. Hoare, "Quicksort," The Computer Journal 5(1) (1962), 10–16.
- J. L. Bentley & M. D. McIlroy, "Engineering a sort function," Software: Practice and Experience 23(11) (1993), 1249–1265.
- M. D. McIlroy, "A killer adversary for quicksort," Software: Practice and Experience (1999).
- S. Wild & M. E. Nebel, "Average case analysis of Java 7's dual pivot quicksort," ESA 2012, LNCS 7501, 825–836.
- O. R. L. Peters, "Pattern-defeating quicksort," arXiv:2106.05123 (2021).