Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 2nln⁡n2n \ln n 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, E[Cn]=2(n+1)Hn−4n\E[C_n] = 2(n+1)H_n - 4n, and describe how concentrated CnC_n is: its variance, its limit law and its tails.
  • Quantify pivot sampling (median of 3 lowers 2nln⁡n2n \ln n to 127nln⁡n\tfrac{12}{7} n \ln n) 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 kk is uniform on 1,…,n1, \dots, n, partitioning costs n−1n - 1 comparisons, and the two sides are independent random instances of sizes k−1k - 1 and n−kn - k. The Optimized lesson proved the mean with indicator variables; the recurrence gives it too, and it is the route to the variance.

DerivationSolving the quicksort recurrence
  1. cn=n−1+2n∑k=0n−1ckc_n = n - 1 + \frac{2}{n} \sum_{k=0}^{n-1} c_k

    Recurrence. Write cn=E[Cn]c_n = \E[C_n] with c0=0c_0 = 0. Averaging over the pivot's rank, both sides range over the same sizes:

  2. ncn−(n−1)cn−1=2(n−1)+2cn−1⟹ncn=(n+1)cn−1+2(n−1)n c_n - (n-1) c_{n-1} = 2(n - 1) + 2 c_{n-1} \quad\Longrightarrow\quad n c_n = (n+1) c_{n-1} + 2(n-1)

    Remove the sum. Multiply by nn, and subtract the same identity for n−1n - 1:

  3. cnn+1=cn−1n+2(n−1)n(n+1)=∑k=1n2(k−1)k(k+1)=∑k=1n(4k+1−2k)\frac{c_n}{n+1} = \frac{c_{n-1}}{n} + \frac{2(n-1)}{n(n+1)} = \sum_{k=1}^{n} \frac{2(k-1)}{k(k+1)} = \sum_{k=1}^{n} \left( \frac{4}{k+1} - \frac{2}{k} \right)

    Telescope. Divide by n(n+1)n(n+1); the left side becomes a difference of consecutive terms:

  4. cn=(n+1)(2Hn−4+4n+1)=2(n+1)Hn−4nc_n = (n+1)\left(2H_n - 4 + \frac{4}{n+1}\right) = 2(n+1)H_n - 4n

    Close the sum. ∑k≤n4k+1=4Hn+1−4=4Hn+4n+1−4\sum_{k \le n} \frac{4}{k+1} = 4H_{n+1} - 4 = 4H_n + \frac{4}{n+1} - 4, so the sum is 2Hn−4+4n+12H_n - 4 + \frac{4}{n+1}. Checked in exact rational arithmetic for every n≤2000n \le 2000:

A weaker statement has a five-line proof. Follow one key xx. A partition round is good for xx if the pivot of xx's range has a rank in the middle half, which happens with probability at least 12\tfrac12, independently of earlier rounds, and then xx's range shrinks to at most 34\tfrac34 of its size. After log⁡4/3n\log_{4/3} n good rounds, xx is alone. A Chernoff bound makes fewer than that many good rounds among the first cln⁡nc \ln n rounds unlikely, with probability at most n−2n^{-2} for a suitable constant cc. The key is compared once per round, so a union bound over the nn keys gives Cn=O(nlog⁡n)C_n = O(n \log n) with high probability, at least 1−1/n1 - 1/n.

Predict before you look

For large nn, how many times the counting bound log⁡2n!\log_2 n! does randomized quicksort spend on average? Give the limit of E[Cn]/log⁡2n!\E[C_n] / \log_2 n!.

Show the answer

1.39

E[Cn]∼2nln⁡n=(2ln⁡2) nlog⁡2n\E[C_n] \sim 2n \ln n = (2 \ln 2)\, n \log_2 n and log⁡2n!∼nlog⁡2n\log_2 n! \sim n \log_2 n, so the ratio tends to 2ln⁡2≈1.3862 \ln 2 \approx 1.386: about 39% above the minimum. Median-of-three pivots cut the excess to about 19%. The limit is approached slowly, since the −2.85n-2.85n term matters for any practical nn.

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 2t+12t + 1 keys, the expected count is nln⁡n/(H2t+2−Ht+1)n \ln n / (H_{2t+2} - H_{t+1}) to first order, which tends to the counting bound nlog⁡2nn \log_2 n as the sample grows:

PivotCoefficient of nln⁡nn \ln nCoefficient of nlog⁡2nn \log_2 n
random key21.386
median of 312/7≈1.71412/7 \approx 1.7141.188
median of 51.6221.124
median of 71.5761.092
median of 211.4901.033
The same constants appear in Wild's analysis of quicksort with equal keys (2018). Optimal sample sizes grow like n\sqrt{n}. Libraries sample only on large ranges: Bentley and McIlroy's 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.
python
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, less

Run against a median-of-three quicksort with Lomuto partitioning, like the widget's, on n=1000n = 1000 keys, this comparison function forces 251,000 comparisons (about n2/4n^2/4), 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 ≤\le pivot to the left. With all keys equal, each partition peels off only the pivot, and the sort costs exactly (n2)\binom{n}{2} comparisons.
  • Hoare stops both scans at keys equal to the pivot and swaps them, so the scans meet near the middle: balanced splits and O(nlog⁡n)O(n \log n), 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.
python
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 - 1

The comment is the invariant; the keys in a[i..gt]a[i..gt] are not yet classified. Tested on thousands of random arrays with few and many distinct values.

InputLomutoHoareThree-wayMultinomial bound
4,000 equal keys7,998,000about 55,0008,000—
10410^4 keys drawn from 10 valuesabout 5.0×1065.0 \times 10^6about 1.6×1051.6 \times 10^5about 6.5×1046.5 \times 10^4about 3.3×1043.3 \times 10^4
Comparisons in one run of each partition scheme with random pivots. Three-way counts two comparisons for a key that is not smaller than the pivot, as the code above does; 7,998,000=(40002)7{,}998{,}000 = \binom{4000}{2} exactly.
Check your understanding

Why is quicksort with Lomuto's partition quadratic on nn equal keys, while Hoare's partition gives O(nlog⁡n)O(n \log n)?

  1. Lomuto compares every pair of keys twice
  2. Hoare's scans skip keys equal to the pivot without comparing them
  3. Lomuto puts every key ≤\le 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
  4. Lomuto's random pivot is not uniformly distributed
Show the answer

C. Lomuto puts every key ≤\le 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 n−1n - 1 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 Ω(nε)\Omega(n^\varepsilon) copies of each value: median-of-kk three-way quicksort is asymptotically ln⁡2/(Hk+1−H(k+1)/2)\ln 2 / (H_{k+1} - H_{(k+1)/2}) 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 p<qp < q into three parts, and Java 7 adopted it in 2011 for sorting arrays of primitive types. Wild and Nebel (2012) computed its average exactly: 1.9nln⁡n−2.46n+O(ln⁡n)1.9n \ln n - 2.46n + O(\ln n) comparisons and 0.6nln⁡n+0.08n+O(ln⁡n)0.6n \ln n + 0.08n + O(\ln n) swaps, against 2nln⁡n2n \ln n comparisons and about 13nln⁡n\tfrac13 n \ln n 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 1.8nln⁡n1.8n \ln n comparisons.

A depth limit. Introsort (Musser, 1997) runs quicksort but counts the recursion depth; past about 2log⁡2n2 \log_2 n 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 O(nlog⁡n)O(n \log n). It is the usual implementation of C++'s std::sort.

python
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 O(nlog⁡n)O(n \log n).

Key takeaways

  • The quicksort recurrence telescopes to E[Cn]=2(n+1)Hn−4n≈1.39 nlog⁡2n\E[C_n] = 2(n+1)H_n - 4n \approx 1.39\, n \log_2 n; the standard deviation is only about 0.65n0.65n, and Cn=O(nlog⁡n)C_n = O(n \log n) with high probability.
  • Pivot sampling lowers the constant: the median of 3 gives 127nln⁡n≈1.19 nlog⁡2n\tfrac{12}{7} n \ln n \approx 1.19\, n \log_2 n, and larger samples approach nlog⁡2nn \log_2 n, but sampling only pays on large ranges.
  • Every deterministic pivot rule has an adversary (McIlroy's gas trick forces about n2/4n^2/4 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.

Question 1

Randomized quicksort sorts 10610^6 distinct keys, with about 2.48×1072.48 \times 10^7 comparisons on average. Roughly how large is the standard deviation of the comparison count?

  1. About 6.5×1056.5 \times 10^5, near 0.65n0.65n: under 3% of the mean
  2. About 5×1065 \times 10^6, about 20% of the mean
  3. About 10310^3, near n\sqrt{n}
  4. About 2.5×1072.5 \times 10^7, as large as the mean
Show the answer

A. About 6.5×1056.5 \times 10^5, near 0.65n0.65n: under 3% of the mean

Var⁡[Cn]≈(7−2π2/3) n2≈0.42 n2\operatorname{Var}[C_n] \approx (7 - 2\pi^2/3)\, n^2 \approx 0.42\, n^2, so the standard deviation is about 0.65n=6.5×1050.65n = 6.5 \times 10^5: about 2.6% of the mean. The mean grows like nlog⁡nn \log n and the spread only like nn, so the relative spread shrinks as nn grows.

Question 2

Choosing the pivot as the median of three random keys changes quicksort's expected comparisons, to first order, from 2nln⁡n2n \ln n to…

  1. nlog⁡2nn \log_2 n, the counting bound
  2. 127nln⁡n≈1.19 nlog⁡2n\tfrac{12}{7} n \ln n \approx 1.19\, n \log_2 n
  3. 32nln⁡n\tfrac32 n \ln n
  4. nothing: one sample cannot change the constant
Show the answer

B. 127nln⁡n≈1.19 nlog⁡2n\tfrac{12}{7} n \ln n \approx 1.19\, n \log_2 n

For a sample of 2t+12t + 1 the constant is 1/(H2t+2−Ht+1)1/(H_{2t+2} - H_{t+1}); with t=1t = 1 that is 1/(H4−H2)=1/(7/12)=12/71/(H_4 - H_2) = 1/(7/12) = 12/7. Larger samples approach nlog⁡2nn \log_2 n, but only in the limit.

Question 3

Why does introsort switch to heapsort once the recursion depth exceeds about 2log⁡2n2 \log_2 n?

  1. Heapsort is faster than quicksort on random data
  2. 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 O(nlog⁡n)O(n \log n) in the worst case
  3. To keep the sort stable
  4. 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 O(nlog⁡n)O(n \log n) in the worst case

Balanced splits finish within about log⁡2n\log_2 n levels, so the limit is reached only after many bad splits. Each level of partitioning costs O(n)O(n), the depth is capped at O(log⁡n)O(\log n), and heapsort's O(mlog⁡m)O(m \log m) on the leftover ranges keeps the total at O(nlog⁡n)O(n \log n).

Question 4

Yaroslavskiy's dual-pivot quicksort makes about 1.9nln⁡n1.9n \ln n comparisons and 0.6nln⁡n0.6n \ln n swaps on average, against 2nln⁡n2n \ln n and 13nln⁡n\tfrac13 n \ln n for classic quicksort, yet it runs faster. What is the accepted explanation?

  1. Comparisons are the only cost that matters, and it makes 5% fewer
  2. Swaps are free on modern hardware
  3. It scans fewer elements in total, so less data moves through the memory hierarchy, which costs more than the extra swaps
  4. 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).