To read the median of a million numbers, any sort needs at least 18.5 million comparisons. Quickselect needs about 3.4 million on average, because it throws away the side it does not need.
Pick a method and press Run. Watch which bars each one has to touch to find the median. Then we build, piece by piece, the scan, quickselect, the median of medians and the two-heap stream.
You need the partition step of quicksort and a little Python. We build the rest from zero.
Based on Chapter 9 of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (CLRS). Before: Sorting in Linear Time. It builds on Quicksort.
Illustrative: 24 distinct numbers, the median is the 12th smallest. Counts come from this page's code: a top-down merge sort, quickselect with a random pivot, and median of medians with groups of five. The million-element figures above are the sorting bound lg(n!) and the quickselect average 2(1 + ln 2)n.
Chapter 0
Name the selection problem and see how much less it asks than a sort
You have one million response times from the last hour. Your dashboard needs the 95th percentile: the value that 95% of the times stay under. That is the 950,000th smallest value. You need one number, not a sorted list.
The rank of an element is its position in sorted order, counted from 1. The element of rank k is the k-th order statistic. Rank 1 is the minimum and rank n is the maximum. The median is the middle one; for even n, CLRS takes the lower middle, rank n/2. The selection problem: given n numbers and a rank k, return the element of rank k.
Sorting solves it, then reads position k. But a sort pins every element to its place. Selection only has to prove two facts: k − 1 elements are smaller than the answer, and the rest are larger. Their order inside each side does not matter.
The top row is the array as it arrives. The bottom row is the output. Switch between select and sort, then drag k.
Illustrative random numbers. The sort count is the lower bound for any comparison sort, lg(n!) rounded up. The select count is the n − 1 comparisons needed to check every other element against the answer.
With numbers: n = 15. Any comparison sort must tell apart 15! orders, so it needs at least lg(15!) ≈ 40.3, that is 41 comparisons. Selection needs at least 14, one per other element. At n = 106 the sort bound is about 18.5 million. This lesson builds selection methods that stay near a few times n.
| Rank k | Name | Comparisons | Chapter |
|---|---|---|---|
| 1 or n | minimum or maximum | exactly n − 1 | 1 |
| 1 and n together | both ends | about 1.5n, not 2n | 1 |
| any k | quickselect | about 3.4n on average for the median | 2, 3 |
| any k | median of medians | a constant times n, always | 4, 5 |
The failure: sorting on every query. Symptom: a percentile panel slows down as traffic grows, faster than the data does. Measure: time one query at n and at 10n; a sort grows by more than 10 times. Fix: select, or keep a structure that answers the rank directly (Chapter 7).
Chapter 1
Count the comparisons a minimum needs, then find both ends for three per pair
Find the shortest person in a room. You walk past each person once and remember the shortest so far. That is one comparison per person after the first: n − 1 comparisons.
No method does better. Think of a knockout tournament. Every player except the champion must lose at least one match, and each comparison has one loser. So n − 1 players need at least n − 1 matches.
The tournament also finds the second smallest cheaply. The runner-up lost only to the winner, and the winner played ⌈lg n⌉ matches. Run a small tournament among those losers. The total is n + ⌈lg n⌉ − 2. For n = 8 that is 9 comparisons, against 13 for two plain scans.
Now you need the minimum and the maximum. Two scans cost 2n − 2. The pair trick takes elements two at a time. First compare the pair with each other. The smaller one can only be a new minimum, the larger only a new maximum. So it plays one contest each: three comparisons per pair, not four.
Call the number of elements n and the comparisons the pair trick makes C. For even n, the first pair costs 1 and each later pair costs 3. For odd n, the first element starts as both ends and each pair costs 3.
C equals the ceiling of three n over two, minus two.
Multiply n by 3 and halve it. Round up. Take away 2. That is C, the cost of both ends.
n = 8: C = 12 − 2 = 10, against 2n − 2 = 14. n = 100: C = 148, against 198. The saving tends to 25%.
Compare the outlined pair first. Its smaller member meets the running minimum (blue); its larger member meets the running maximum (pink). Step through and watch both counters.
The first array, 47 12 83 5 29 61 38 91, is the worked example below. New numbers are random.
| Pair | Pair compare | Min after | Max after | Comparisons so far |
|---|---|---|---|---|
| 47, 12 | 12 < 47, start both ends | 12 | 47 | 1 |
| 83, 5 | 5 meets 12, 83 meets 47 | 5 | 83 | 4 |
| 29, 61 | 29 meets 5, 61 meets 83 | 5 | 83 | 7 |
| 38, 91 | 38 meets 5, 91 meets 83 | 5 | 91 | 10 |
The failure: a counter that disagrees with the formula. Symptom: your count for n = 8 is 12. Measure: count the first pair alone; it should cost 1. Fix: start both ends from the first pair, or from the first element when n is odd.
Chapter 2
Reuse quicksort's partition and follow only the side that holds rank k
Recall partition from quicksort. It picks a pivot, moves every smaller element to its left and every larger one to its right. The pivot then sits at its final sorted place. If r − 1 elements went left, the pivot has rank r.
Quicksort then sorts both sides. For selection you need only one. If k = r, the pivot is the answer. If k < r, the answer is on the left, with the same rank. If k > r, it is on the right, and its rank there changes. This method is quickselect; CLRS calls it RANDOMIZED-SELECT.
Call the rank you seek k, the pivot's rank in the current window r, and the rank to seek inside the right side k′.
k-prime equals k minus r.
The pivot and the left side hold r elements, all smaller than anything on the right. Drop them, and subtract r from k. The answer has rank k-prime among what is left.
Seek k = 5 in [7, 3, 9, 1, 5, 8, 2, 6, 4]. The pivot 4 lands at r = 4. Since 5 > 4, go right with k′ = 5 − 4 = 1: the smallest of [5, 8, 9, 6, 7].
The full trace, with the CLRS partition (the pivot is the last element of the window):
| Window | Pivot | Rank r | Seek | Decision | Comparisons |
|---|---|---|---|---|---|
| 7 3 9 1 5 8 2 6 4 | 4 | 4 | k = 5 | go right, k′ = 1 | 8 |
| 5 8 9 6 7 | 7 | 3 | k = 1 | go left | 4 |
| 5 6 | 6 | 2 | k = 1 | go left | 1 |
| 5 | none | 1 | k = 1 | answer: 5 | 0 |
Total: 8 + 4 + 1 = 13 comparisons. Each partition of a window of m elements costs m − 1.
The bright bars are the live window. Purple is the pivot; blue went left of it, pink went right. Set k, then press Step until the answer turns warm.
The pivot is the last element of the window, as in the CLRS partition, so the trace is repeatable. Real quickselect first swaps a random element into that place.
pythondef quickselect(A, k): # k is 1-based; A is changed in place lo, hi = 0, len(A) - 1 while lo < hi: r_i = random.randint(lo, hi); A[r_i], A[hi] = A[hi], A[r_i] q = partition(A, lo, hi) # pivot now at index q r = q - lo + 1 # its rank in the window if k == r: return A[q] if k < r: hi = q - 1 else: k, lo = k - r, q + 1 # k-prime = k - r return A[lo]
The failure: forgetting k′. Symptom: small k works and large k returns the wrong value or an index error. Measure: compare against sorted(A)[k-1] for every k. Fix: subtract r whenever you move right.
Chapter 3
Add up the shrinking windows, then meet the rare run that does not shrink
Each round scans its whole window, then keeps a part of it. Suppose every pivot is lucky and keeps half. The rounds scan n, then n/2, then n/4. That sum never passes 2n. Quicksort keeps both halves, so every level scans all n, and there are about lg n levels.
Call the fraction of the window each round keeps s, and the total number of elements scanned over all rounds W.
W equals n times one plus s plus s squared and so on, which equals n over one minus s.
Each round scans s times the round before. Add the rounds up. The total W is n divided by one minus s, a fixed multiple of n.
Lucky halves, s = 1/2: W = n/(1/2) = 2n. Keep three quarters, s = 3/4: W = 4n. For n = 1,000 that is 2,000 and 4,000 elements scanned.
Real pivots are random, not lucky. Call a pivot good if its rank is in the middle half of the window. Then it keeps at most 3/4. Half of all ranks are good, so a good pivot comes on average every 2 rounds. Each stretch until a good pivot scans at most twice its window. With s = 3/4, the expected work is at most 2 × 4n = 8n.
That bound is loose. Measured on random arrays of 1,000, the median costs about 3,400 comparisons, close to the known average 2(1 + ln 2)n ≈ 3.39n. The minimum costs about 2n.
Each run counts its comparisons, divided by n. Teal bars are the spread; the line is the average. Try the minimum, then turn on the bad pivot.
Illustrative random arrays of distinct numbers, measured by this page's quickselect (one comparison per element per partition).
The worst case is real. If every pivot is the largest element, each round drops one element. The rounds scan n − 1, then n − 2, down to 1: n(n − 1)/2 comparisons. For n = 1,000 that is 499,500. A fixed last-element pivot on sorted input does this every time; a random pivot makes it vanishingly rare.
The failure: many equal values. Symptom: an array of all 5s runs in quadratic time even with random pivots. Measure: the window shrinks by one per round. Fix: a three-way partition that groups the elements equal to the pivot and stops if k lands among them.
Chapter 4
Build a pivot that always leaves at least 30% on each side, with no coin flips
A guarantee needs a pivot that is never near the ends. In 1973 Blum, Floyd, Pratt, Rivest and Tarjan built one: median of medians, or BFPRT. CLRS calls it SELECT.
Why is x safe? Draw each group as a sorted column and order the columns by median. Half the medians are at most x, and each sits on two smaller elements.
Each column is a group of five. Step through: sort each column, line the columns up by median, then see which elements are surely below or above x.
n = 25 uses the worked array below; the other sizes are random. Every group is full here, so the blocks hold 3 × (number of columns + 1)/2 elements, x included.
Call the number of elements surely larger than x G.
G is at least three times the ceiling of half the ceiling of n over five, minus two. That is at least three n over ten, minus six.
Count the groups whose median is at least x. Drop two to be safe. Each other group holds 3 elements at least x, so G is 3 times the count.
n = 1,000: 200 groups, half is 100, minus 2 is 98, times 3 is G = 294 = 3n/10 − 6. The recursion then sees at most 1,000 − 294 = 706 elements.
Worked trace, in groups of five: 31 72 14 88 45 | 63 27 91 36 58 | 82 19 50 75 43 | 11 67 33 96 54 | 28 85 40 69 22. The group medians are 45, 58, 50, 54 and 40, so x = 50. Then 13 elements are at most 50: rank 13, the median.
Call the worst-case time T(n) and the cost per element of grouping and partitioning a.
T of n is at most T of n over five, rounded up, plus T of seven n over ten plus six, plus a n.
One call does a times n work, then makes two smaller calls. Their sizes add to about 0.9n. So each level costs at most 0.9 times the level above.
n = 1,000: the two calls get 200 and 706 elements, 906 in all. With s = 0.9 in W = n/(1 − s), the levels add to at most about 10 × a × 1,000. Linear, always.
The failure: finding the median of the medians by sorting them. Symptom: the run is correct but grows like n lg n. Measure: time n and 10n. Fix: step 3 must call SELECT itself, so the medians cost T(n/5).
Chapter 5
Compute the kept fraction for each group size and find the smallest that stays under 1
Nothing in the method fixes the group size at 5. Try groups of g. The recurrence keeps its shape: one call on the g-th part of the elements, one call on the larger side. The question is whether the two parts add to less than the whole.
For odd g, a group median sits on (g + 1)/2 elements of its group. Half the groups count, so about (g + 1)/(4g) of all elements are surely below x. Call the fraction of n that the two recursive calls receive together s(g).
s of g equals one over g, plus three g minus one, over four g.
Add the share for the medians call to the share for the larger side. If the sum s is below 1, the levels shrink and W = n/(1 − s) is linear. If it is 1, every level costs n again.
g = 5: 1/5 + 14/20 = 0.2 + 0.7 = 0.9, so W = 10n. g = 3: 1/3 + 8/12 = 1, no shrinking. g = 7: 1/7 + 20/28 = 6/7, so W = 7n.
| Group size g | Medians call | Larger side | Sum s(g) | Total work |
|---|---|---|---|---|
| 3 | 0.333 | 0.667 | 1.000 | grows like n lg n |
| 5 | 0.200 | 0.700 | 0.900 | 10 × a × n |
| 7 | 0.143 | 0.714 | 0.857 | 7 × a × n |
| 9 | 0.111 | 0.722 | 0.833 | 6 × a × n |
Each bar is one level of the recursion on 1,000 elements: its total size. Pick a group size and watch whether the bars shrink.
Level i has total size 1,000 × s(g) to the i, the worst case of the recurrence with the small constants dropped.
So 5 is the smallest odd size that works. Larger groups also work and pass less down. But each group costs more to sort: insertion sort needs up to 10 comparisons for 5 elements and 21 for 7. Even sizes add nothing. With g = 4, the lower median gives a sum of exactly 1, as g = 3 does.
The failure: groups of 3. Symptom: the guarantee holds but the time grows like n lg n, no better than sorting. Measure: add the level sizes; each level is n again. Fix: use groups of 5 or more.
Chapter 6
Run sort, quickselect and median of medians on the same arrays and compare the counts
Theory gives growth rates. It does not say who wins at n = 100. So race them. Each trial makes one random array, and all three methods find the same rank in it. Each dot is one trial; the tick is the average.
Grey sorts, teal is quickselect, yellow is median of medians. Set n and the rank, then run 100 trials. Turn on the bad input to break quickselect's luck.
Measured by this page's code on random distinct numbers. Merge sort counts its merge comparisons. Median of medians sorts each group by insertion sort and counts that work.
| n, median | Merge sort | Quickselect | Median of medians |
|---|---|---|---|
| 100 | about 540 | about 305 | about 580 |
| 1,000 | about 8,700 | about 3,400 | about 7,300 |
| 10,000 | about 120,000 | about 36,000 | about 79,000 |
Three patterns stand out:
Libraries combine the two. Introselect, proposed by David Musser in 1997, runs quickselect and watches the depth. If the depth grows too large, it switches to a method with a guarantee. Musser named median of medians as that fallback. C++ std::nth_element and NumPy's partition use introselect.
The failure: a fixed pivot on input you do not control. Symptom: quickselect is fast in tests and quadratic on sorted production data. Measure: turn on the bad input above. Fix: a random pivot, or introselect.
Chapter 7
Keep the median current as numbers arrive, with two heaps that hold the two halves
Now the numbers never stop. A latency monitor gets a new value every millisecond and must show the median at once. Running quickselect on every arrival costs n each time.
Split the values into two halves. The smaller half lives in a max-heap called lo: its top is its largest value. The larger half lives in a min-heap called hi: its top is its smallest value. The median sits at the tops.
Keep three rules after every insert:
To add a value: push it into lo, move lo's top to hi, and if hi is now bigger, move hi's top back to lo. Each move is one heap operation, so an insert costs O(log n). The median is lo's top when n is odd, and the mean of both tops when n is even.
Blue is lo, the smaller half; pink is hi, the larger half. The warm box is the median. Add values and watch the tops.
Illustrative values from 1 to 99. The heaps hold up to 30 values, then the device starts over.
| Value in | lo (max-heap) | hi (min-heap) | Median |
|---|---|---|---|
| 5 | 5 | empty | 5 |
| 15 | 5 | 15 | (5 + 15)/2 = 10 |
| 1 | 1, 5 | 15 | 5 |
| 3 | 1, 3 | 5, 15 | (3 + 5)/2 = 4 |
| 8 | 1, 3, 5 | 8, 15 | 5 |
The failure: skipping the move back. Symptom: the median drifts upward and tracks the running maximum. Measure: compare with the median of the sorted prefix after each insert. Fix: rebalance whenever hi outnumbers lo.
Chapter 8
Use selection for dashboards, for the largest K items and for the best place to build
Percentiles. The p99 of n values is the element of rank ⌈0.99n⌉. Three percentiles cost three quickselect calls, still linear. Why not the mean? Take 99 requests of 10 ms and one stuck for 10 seconds. The mean is 109.9 ms, the median stays at 10 ms, and the p99 shows the stuck one.
Top K. Quickselect for rank n − K + 1 leaves the K largest to its right, unsorted, in linear time. For a stream that does not fit in memory, keep a min-heap of the K best so far.
| Way to get the top K | Time | Memory | Use when |
|---|---|---|---|
| Sort, take K | n lg n | the array | you also need them in order |
| Quickselect | n on average | the array | all the data is in memory |
| Min-heap of size K | n lg K | K items | the data is a stream |
Five shops lie on one road, at 2, 5, 9, 12 and 20 km. They need 3, 1, 2, 2 and 5 deliveries a day. Where should the depot go so that the total distance driven is smallest? Call the shop positions xi, their delivery counts wi and the depot position p.
C of p equals the sum over i of w-i times the absolute value of x-i minus p.
For each shop, multiply its distance from p by its weight w-i. Add them up. Move p one km right: C changes by the weight to the left minus the weight to the right. Stop where that turns positive. That point is the weighted median.
The weights total 13. Left of 12 they sum to 6, below half; up to 12 they reach 8, past half. So p = 12: C = 3 × 10 + 1 × 7 + 2 × 3 + 0 + 5 × 8 = 83 km. The weighted mean, 11.77 km, gives 83.2 km.
Circles are shops, sized by deliveries. The curve is the total distance C(p). Drag the depot, then switch the weights.
Illustrative shops and weights. The curve is exact for these numbers.
The failure: averaging when the cost is a distance. Symptom: a far, busy shop drags the depot toward it. Measure: compute C at the mean and at the weighted median. Fix: select the weighted median, in linear time with a quickselect that tracks weights.
Chapter 9
Keep the numbers, the code and the bounds in one place
Selection finds rank k by proving a split, not an order. Quickselect partitions and keeps one side, linear on average. Median of medians picks a pivot with a 30% floor, linear always. Two heaps keep a running median.
| Term or number | Meaning |
|---|---|
| k-th order statistic | the element of rank k; the median has rank ⌈n/2⌉ (the lower median) |
| n − 1 | comparisons for the minimum; no method does better |
| n + ⌈lg n⌉ − 2 | comparisons for the second smallest, by tournament |
| ⌈3n/2⌉ − 2 | comparisons for both minimum and maximum, by pairs |
| k′ = k − r | the rank to seek after moving right of a pivot of rank r |
| 2(1 + ln 2)n ≈ 3.39n | average comparisons of quickselect for the median |
| n(n − 1)/2 | worst case of quickselect: 499,500 at n = 1,000 |
| 3n/10 − 6 | elements surely on each side of the median of medians |
| s(5) = 0.9 | share passed down per level with groups of 5; total about 10 times one level |
| lg(n!) | fewest comparisons any sort needs: about 18.5 million at n = 106 |
| O(log n), O(1) | two-heap insert and two-heap median |
pythonimport random def select(A, k): # k-th smallest, 1-based; median of medians if len(A) <= 5: return sorted(A)[k - 1] meds = [sorted(A[i:i + 5])[(len(A[i:i + 5]) - 1) // 2] for i in range(0, len(A), 5)] x = select(meds, (len(meds) + 1) // 2) # the pivot no input can break L = [v for v in A if v < x]; E = [v for v in A if v == x]; R = [v for v in A if v > x] if k <= len(L): return select(L, k) if k <= len(L) + len(E): return x return select(R, k - len(L) - len(E)) # k-prime = k - r def top_k(A, K): # the K largest, unordered x = select(A, len(A) - K + 1) big = [v for v in A if v > x] return big + [x] * (K - len(big))
| Problem | Fewest comparisons |
|---|---|
| Minimum | n − 1, matched by a scan |
| Second smallest | n + ⌈lg n⌉ − 2, matched by a tournament |
| Minimum and maximum | ⌈3n/2⌉ − 2, matched by pairs |
| Median | a little over 2n; the best known method uses about 2.95n (Dor and Zwick) |
| Sorting | lg(n!), about n lg n |
Credit: this lesson follows Chapter 9, Medians and Order Statistics, of Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). The worst-case method is from Blum, Floyd, Pratt, Rivest and Tarjan, "Time Bounds for Selection" (1973).
Explain it back with Present or Teach, or go back to the race and predict each count before you press Run.