Medians and Order Statistics

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.

Find the median three ways

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

Find One Element Without Sorting

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.

Compare what each one must learn

The top row is the array as it arrives. The bottom row is the output. Switch between select and sort, then drag k.

6
15

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 kNameComparisonsChapter
1 or nminimum or maximumexactly n − 11
1 and n togetherboth endsabout 1.5n, not 2n1
any kquickselectabout 3.4n on average for the median2, 3
any kmedian of mediansa constant times n, always4, 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).

The road

  1. Min, max and the pair trick: n − 1 comparisons, and both ends for 3n/2.
  2. Quickselect: partition, then keep one side (the hero's teal run).
  3. Why it averages linear time: a shrinking sum, and the worst case.
  4. Median of medians: a pivot that is never too lopsided (the hero's yellow run).
  5. Why groups of five: the fraction that must stay under 1.
  6. The selection race: all three methods on the same arrays.
  7. The streaming median: two heaps for numbers that keep arriving.
  8. Percentiles, top K, the weighted median: where selection does real work.
  9. The field guide: numbers, code and links.
You need the 950,000th smallest of one million numbers. What must a selection algorithm establish?

Chapter 1

Min, Max and the Pair Trick

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.

Both ends at once

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.

Say it aloud

C equals the ceiling of three n over two, minus two.

C
C the number of comparisons the pair trick makes to find both the minimum and the maximum.
n
n the number of elements, 2 or more.
⌈ · ⌉
the ceiling of round up to the next whole number. It makes one formula fit odd and even n.
− 2
minus two the saving at the start: the first pair, or the first element, needs no contest against a running champion.
In plain words

Multiply n by 3 and halve it. Round up. Take away 2. That is C, the cost of both ends.

With numbers

n = 8: C = 12 − 2 = 10, against 2n − 2 = 14. n = 100: C = 148, against 198. The saving tends to 25%.

Run the pair trick

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.

PairPair compareMin afterMax afterComparisons so far
47, 1212 < 47, start both ends12471
83, 55 meets 12, 83 meets 475834
29, 6129 meets 5, 61 meets 835837
38, 9138 meets 5, 91 meets 8359110

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.

How many comparisons does the pair trick need for both the minimum and the maximum of 100 elements?

Chapter 2

Quickselect: Partition, Then Keep One Side

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′.

Say it aloud

k-prime equals k minus r.

k′
k-prime the rank to seek inside the right side, used only when k is larger than r.
k
k the rank you seek in the current window, from 1 to the window size.
r
r the pivot's rank in the current window: the pivot plus everything to its left.
In plain words

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.

With numbers

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):

WindowPivotRank rSeekDecisionComparisons
7 3 9 1 5 8 2 6 444k = 5go right, k′ = 18
5 8 9 6 773k = 1go left4
5 662k = 1go left1
5none1k = 1answer: 50

Total: 8 + 4 + 1 = 13 comparisons. Each partition of a window of m elements costs m − 1.

Step quickselect toward rank k

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.

5

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.

You seek k = 9 in a window of 12. The pivot lands at rank r = 4. What next?

Chapter 3

Why Quickselect Averages Linear Time

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.

Say it aloud

W equals n times one plus s plus s squared and so on, which equals n over one minus s.

W
W the total work: elements scanned, summed over every round.
n
n the number of elements at the start.
s
s the fraction of the window a round keeps, between 0 and 1. Round i scans n times s to the i.
n/(1 − s)
n over one minus s the sum of the endless shrinking series. It is finite only when s is less than 1.
In plain words

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.

With numbers

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.

Run quickselect four hundred times

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.

Each round keeps at most 3/4 of the window. What does the work sum stay under?

Chapter 4

Median of Medians: A Pivot You Can Trust

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.

  1. Cut the n elements into groups of 5. The last group may be short.
  2. Sort each group and take its middle element, the group median.
  3. Call SELECT on the group medians to find their median, x.
  4. Partition the whole array around x. Say x lands at rank r.
  5. If k = r, return x. Otherwise recurse on one side, as in quickselect.

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.

Find the pivot no input can break

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.

Say it aloud

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.

G
G how many elements are surely larger than x. The same count is surely smaller.
⌈⌈n/5⌉/2⌉
the ceiling of half the ceiling of n over five the groups whose median is at least x: half the groups, rounded up.
− 2
minus two leave out x's own group and the short last group, which may not give 3.
3
three times each counted group gives its median and the two elements above it.
3n/10 − 6
three n over ten, minus six a simpler floor: about 30% of n.
In plain words

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.

With numbers

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.

Say it aloud

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.

T(n)
T of n the worst-case time of SELECT on n elements.
T(⌈n/5⌉)
T of the ceiling of n over five step 3: select among the group medians.
T(7n/10 + 6)
T of seven n over ten plus six step 5: recurse on the larger side, at most n minus G elements.
a n
a times n steps 1, 2 and 4: sorting the small groups and the partition, a fixed cost per element.
In plain words

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.

With numbers

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).

For n = 1,000, what is the largest side SELECT can be left with after partitioning around the median of medians?

Chapter 5

Why Groups of Five

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).

Say it aloud

s of g equals one over g, plus three g minus one, over four g.

s(g)
s of g the share of n that one level passes down, for groups of g (an odd number). It must be below 1.
1/g
one over g the call on the group medians: one median per group.
(3g − 1)/(4g)
three g minus one, over four g the larger side: everything except the (g + 1)/(4g) that is surely on the other side.
In plain words

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.

With numbers

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 gMedians callLarger sideSum s(g)Total work
30.3330.6671.000grows like n lg n
50.2000.7000.90010 × a × n
70.1430.7140.8577 × a × n
90.1110.7220.8336 × a × n

Shrink the levels, or fail to

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.

Why do groups of 3 fail to give linear time?

Chapter 6

The Selection Race

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.

Race three methods on the same arrays

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.

100
50%

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, medianMerge sortQuickselectMedian of medians
100about 540about 305about 580
1,000about 8,700about 3,400about 7,300
10,000about 120,000about 36,000about 79,000

Three patterns stand out:

  1. Sort is steady but grows fastest, about n lg n.
  2. Quickselect is cheapest on average, and its dots spread out: some runs cost twice the mean.
  3. Median of medians has a tight spread but a large constant. At n = 100 it costs about as much as sorting. Its edge grows with n.

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.

Why do libraries not run median of medians on every call?

Chapter 7

The Streaming Median With Two Heaps

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:

  1. Every value in lo is at most every value in hi.
  2. The sizes differ by at most 1.
  3. If one heap is bigger, it is lo.

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.

Feed the two heaps

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 inlo (max-heap)hi (min-heap)Median
55empty5
15515(5 + 15)/2 = 10
11, 5155
31, 35, 15(3 + 5)/2 = 4
81, 3, 58, 155

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.

After the stream 5, 15, 1, 3, lo holds 1 and 3 and hi holds 5 and 15. What is the median?

Chapter 8

Percentiles, Top K and the Weighted Median

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 KTimeMemoryUse when
Sort, take Kn lg nthe arrayyou also need them in order
Quickselectn on averagethe arrayall the data is in memory
Min-heap of size Kn lg KK itemsthe data is a stream

The best place for a depot

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.

Say it aloud

C of p equals the sum over i of w-i times the absolute value of x-i minus p.

C(p)
C of p the total distance driven per day with the depot at p, in km.
Σi
the sum over i add one term for each shop.
wi
w-i the weight of shop i: its deliveries per day.
|xi − p|
the absolute value of x-i minus p the distance from the depot to shop i, never negative.
In plain words

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.

With numbers

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.

Place the depot

Circles are shops, sized by deliveries. The curve is the total distance C(p). Drag the depot, then switch the weights.

6 km

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.

With the depot at 7 km, the weight to the left is 4 and to the right is 9. Moving the depot 1 km right changes C by how much?

Chapter 9

The Field Guide

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 numberMeaning
k-th order statisticthe element of rank k; the median has rank ⌈n/2⌉ (the lower median)
n − 1comparisons for the minimum; no method does better
n + ⌈lg n⌉ − 2comparisons for the second smallest, by tournament
⌈3n/2⌉ − 2comparisons for both minimum and maximum, by pairs
k′ = k − rthe rank to seek after moving right of a pivot of rank r
2(1 + ln 2)n ≈ 3.39naverage comparisons of quickselect for the median
n(n − 1)/2worst case of quickselect: 499,500 at n = 1,000
3n/10 − 6elements surely on each side of the median of medians
s(5) = 0.9share 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

Before you select

  1. Fix the indexing: is k 1-based, and is it the k-th smallest or the k-th largest (rank n − k + 1)?
  2. Ask if you may reorder the input. Quickselect works in place.
  3. Use a random pivot, or a library introselect.
  4. Use a three-way partition if values repeat.
  5. For a stream, use two heaps or a size-K heap.

The core

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))

Lower bounds

ProblemFewest comparisons
Minimumn − 1, matched by a scan
Second smallestn + ⌈lg n⌉ − 2, matched by a tournament
Minimum and maximum⌈3n/2⌉ − 2, matched by pairs
Mediana little over 2n; the best known method uses about 2.95n (Dor and Zwick)
Sortinglg(n!), about n lg n

Keep going

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).

The takeaway. To find one rank, prove a split and throw the other side away. A shrinking sum of windows is what makes it linear.

Explain it back with Present or Teach, or go back to the race and predict each count before you press Run.

Medians and Order Statistics, CLRS Chapter 9
Back to Gleams