Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Linear-Time Selection: Median of Medians

The deterministic O(n) algorithm of Blum, Floyd, Pratt, Rivest and Tarjan.

In 1973, five researchers, four of whom would later receive the Turing Award, proved that the median of nn numbers can be found in linear time without any randomness. Their algorithm fits on half a page. How many comparisons the median really needs is a different story: somewhere between 2n2n and 2.95n2.95n, and nobody has closed the gap.

What you’ll learn

  • State the median-of-medians algorithm (BFPRT) and prove that its pivot has at least 3n/10−63n/10 - 6 elements on each side.
  • Solve T(n)≤T(⌈n/5⌉)+T(7n/10+6)+O(n)T(n) \le T(\lceil n/5 \rceil) + T(7n/10 + 6) + O(n) by substitution, and explain why groups of 3 fail and groups of 7 or more succeed.
  • Prove a 3(n−1)/23(n-1)/2 lower bound for the median with an adversary argument, and place it among the known bounds: (2+ε)n(2 + \varepsilon)n below, 2.95n2.95n above.
  • Explain the role of deterministic selection in practice: a fallback that guarantees linear time when quickselect's pivots go wrong.

The algorithm and its 30/70 guarantee

Quickselect is fast on average, but a run of bad pivots makes it quadratic. Blum, Floyd, Pratt, Rivest and Tarjan (1973) removed the luck: they compute a pivot that is guaranteed to be near the middle, at a cost small enough to keep the total linear. The pivot is the median of medians, found by a recursive call of the algorithm itself.

text
SELECT(A, k):                              # the element of rank k (0-indexed); keys distinct
    if |A| <= 5: return the element of rank k of sorted(A)
    split A into groups of 5 (the last may be smaller)
    M <- the median of each group          # 6 comparisons per full group suffice
    x <- SELECT(M, floor((|M| - 1) / 2))    # the median of the medians
    L <- elements of A smaller than x
    R <- elements of A larger than x
    if k < |L|: return SELECT(L, k)
    if k = |L|: return x
    return SELECT(R, k - |L| - 1)

Two recursive calls per round: one on the ⌈n/5⌉\lceil n/5 \rceil medians to choose the pivot, one on a single side of the partition. A Python transcription, tested against sorting on random inputs, never kept more than 7n/10+67n/10 + 6 elements.

DerivationThe pivot is central
  1. #{groups whose median is≥x}  ≥  ⌈g2⌉\#\{\text{groups whose median is} \ge x\} \;\ge\; \left\lceil \tfrac{g}{2} \right\rceil

    Let g=⌈n/5⌉g = \lceil n/5 \rceil be the number of groups. Since xx is the median of the gg group medians, at least half of those medians are ≥x\ge x:

  2. 3(⌈12⌈n5⌉⌉−2)  ≥  3n10−63\left(\left\lceil \tfrac12 \left\lceil \tfrac{n}{5} \right\rceil \right\rceil - 2\right) \;\ge\; \frac{3n}{10} - 6

    Each such group holds at least 3 elements ≥x\ge x: its median and the two above it. Two groups may fall short, the group of xx itself (which contributes 2 besides xx) and the last, partial group, so the elements greater than xx number at least

  3. max⁡(∣L∣,∣R∣)  ≤  n−(3n10−6)  =  7n10+6\max(\abs{L}, \abs{R}) \;\le\; n - \left(\tfrac{3n}{10} - 6\right) \;=\; \tfrac{7n}{10} + 6

    The same count holds for elements smaller than xx. Whichever side the recursion keeps, it loses at least 3n/10−63n/10 - 6 elements:

Check your understanding

Run the same algorithm with groups of 7. Roughly what fraction of the elements is then guaranteed to lie on each side of the pivot?

  1. 3n/103n/10, as with groups of 5
  2. n/7n/7
  3. 2n/72n/7
  4. 3n/73n/7
Show the answer

C. 2n/72n/7

Half of the n/7n/7 groups have a median ≥x\ge x, and each of those holds 4 elements ≥x\ge x (its median and the three above it): 4⋅n14=2n74 \cdot \tfrac{n}{14} = \tfrac{2n}{7}. The recursion keeps at most 5n/75n/7, and T(n)≤T(n/7)+T(5n/7)+O(n)T(n) \le T(n/7) + T(5n/7) + O(n) is linear, because 17+57=67<1\tfrac17 + \tfrac57 = \tfrac67 < 1.

Solving the recurrence

DerivationProof by substitution
  1. T(n)  ≤  c(n5+1)+c(7n10+6)+an  =  9cn10+7c+anT(n) \;\le\; c\left(\tfrac{n}{5} + 1\right) + c\left(\tfrac{7n}{10} + 6\right) + an \;=\; \tfrac{9cn}{10} + 7c + an

    Assume T(m)≤cmT(m) \le cm for every m<nm < n (strong induction) and substitute, using ⌈n/5⌉≤n/5+1\lceil n/5 \rceil \le n/5 + 1:

  2. T(n)  ≤  cn+(an−c(n10−7))T(n) \;\le\; cn + \left(an - c\left(\tfrac{n}{10} - 7\right)\right)

    Rewrite the right-hand side as cncn plus a remainder that must not be positive:

  3. c(n10−7)  ≥  20a⋅n20  =  anc\left(\tfrac{n}{10} - 7\right) \;\ge\; 20a \cdot \tfrac{n}{20} \;=\; an

    For n≥140n \ge 140 we have n10−7≥n20\tfrac{n}{10} - 7 \ge \tfrac{n}{20}, so c=20ac = 20a makes the remainder at most 0, and T(n)≤cnT(n) \le cn:

  4. ∑i≥0(α+β)i an  =  an1−α−β\sum_{i \ge 0} (\alpha + \beta)^i\, an \;=\; \frac{an}{1 - \alpha - \beta}

    The principle. Whenever T(n)≤T(αn)+T(βn)+O(n)T(n) \le T(\alpha n) + T(\beta n) + O(n) with α+β<1\alpha + \beta < 1, level ii of the recursion tree costs at most (α+β)i⋅an(\alpha + \beta)^i \cdot an, a geometric series. With α+β=1\alpha + \beta = 1 every level costs about anan, and there are Θ(log⁡n)\Theta(\log n) levels.

Group sizeGuaranteed on each sideRecurrenceResult
3about n/3n/3T(n/3)+T(2n/3)+O(n)T(n/3) + T(2n/3) + O(n)Θ(nlog⁡n)\Theta(n \log n)
5about 3n/103n/10T(n/5)+T(7n/10)+O(n)T(n/5) + T(7n/10) + O(n)O(n)O(n), fractions sum to 0.90.9
7about 2n/72n/7T(n/7)+T(5n/7)+O(n)T(n/7) + T(5n/7) + O(n)O(n)O(n), fractions sum to 6/76/7
9about 5n/185n/18T(n/9)+T(13n/18)+O(n)T(n/9) + T(13n/18) + O(n)O(n)O(n), fractions sum to 5/65/6
Groups of 3 fail only for the plain algorithm: Chen and Dumitrescu (2015) gave variants with groups of 3 and 4 that apply the grouping step twice before recursing and do run in linear time.
Predict before you look

Count comparisons in the simple version: 6 per group median and nn for the partition. If C(n)≤C(n/5)+C(7n/10)+6n5+nC(n) \le C(n/5) + C(7n/10) + \tfrac{6n}{5} + n and C(n)=cnC(n) = cn, what is cc?

Show the answer

22

c=c5+7c10+115c = \tfrac{c}{5} + \tfrac{7c}{10} + \tfrac{11}{5} gives c10=115\tfrac{c}{10} = \tfrac{11}{5}, so c=22c = 22. Blum and colleagues' carefully tuned version, PICK, needs at most about 5.43n5.43n, still well above quickselect's average of 3.39n3.39n for the median. That is why libraries keep median of medians as a fallback rather than the default.

How many comparisons does the median need?

Linear time settles the asymptotics; the constant is another matter, and one of the oldest open questions about comparisons. In the comparison model, for the median of nn distinct keys:

BoundComparisonsSource
Upper, deterministic≈5.43 n\approx 5.43\,nBlum, Floyd, Pratt, Rivest & Tarjan (1973), algorithm PICK
Upper, deterministic3n+o(n)3n + o(n)Schönhage, Paterson & Pippenger (1976)
Upper, deterministic2.95 n2.95\,nDor & Zwick (1999)
Lower, deterministic2n−o(n)2n - o(n)Bent & John (1985)
Lower, deterministic(2+ε) n(2 + \varepsilon)\,n for a tiny ε>0\varepsilon > 0Dor & Zwick (2001)
Randomized, expected1.5 n+o(n)1.5\,n + o(n), optimalFloyd & Rivest (1975); matching lower bound by Cunto & Munro (1989)
Deterministic rows are worst-case counts; the last row is an average over the algorithm's random choices, and it beats every deterministic worst case: 1.5n1.5n on average against more than 2n2n in the worst case.
DerivationProof: an adversary that wastes comparisons
  1. #{crucial comparisons}  ≥  n−1\#\{\text{crucial comparisons}\} \;\ge\; n - 1

    Crucial comparisons. Let mm be the median. A comparison of xx with yy is crucial for xx if it is the first to show x>y≥mx > y \ge m or x<y≤mx < y \le m. To certify mm, the algorithm must know, for each x≠mx \ne m, a chain of comparisons leading from xx to mm, and the first link of that chain is crucial for xx. A comparison is crucial for at most one of its two keys, so

  2. fresh:fresh→(L,S),fresh:L→S,fresh:S→L\text{fresh}{:}\text{fresh} \to (L, S), \qquad \text{fresh}{:}L \to S, \qquad \text{fresh}{:}S \to L

    The adversary. It leaves each key unassigned until the key's first comparison, then assigns it to LL (to end above mm) or SS (to end below mm) so that the comparison is crucial for no one: two fresh keys become one LL and one SS; a fresh key compared with an LL key joins SS; one compared with an SS key joins LL. Since L>m>SL > m > S, an LL-versus-SS comparison links neither key to mm.

  3. C(n)  ≥  (n−1)+n−12  =  3(n−1)2C(n) \;\ge\; (n - 1) + \frac{n - 1}{2} \;=\; \frac{3(n - 1)}{2}

    Counting. The adversary can do this until LL or SS holds (n−1)/2(n-1)/2 keys. Every key other than mm must take part in some comparison, so one side does fill up, and each wasted comparison adds at most one key to that side. That forces at least (n−1)/2(n - 1)/2 wasted comparisons on top of the n−1n - 1 crucial ones:

Bent and John (1985) pushed the same style of argument to 2n−o(n)2n - o(n) with a subtler accounting of how much each comparison can reveal, and Dor and Zwick (2001) to (2+ε)n(2 + \varepsilon)n. The upper bounds came from a different direction: Schönhage, Paterson and Pippenger built the median from carefully structured partial orders ("factories" of small sorted pieces), and Dor and Zwick refined those factories to reach 2.95n2.95n.

In practice, and what is still open

Median of medians is rarely the fastest way to select: its constant is several times quickselect's. Its role is a guarantee. Introselect (Musser, 1997) runs quickselect with cheap pivots and switches to a linear-time pivot rule when the range fails to shrink quickly enough, so typical inputs pay quickselect's price and adversarial ones still finish in O(n)O(n). Engineering narrows the gap further: Alexandrescu (2017) designed deterministic selection routines that compete with quickselect in practice.

The history is a small hall of fame: four of the five authors of the 1973 paper, Floyd (1978), Tarjan (1986), Blum (1995) and Rivest (2002), received the Turing Award, each for other work.

Key takeaways

  • Median of medians (BFPRT, 1973) groups the keys by 5 and recursively selects the median of the group medians; that pivot has at least 3n/10−63n/10 - 6 keys on each side.
  • T(n)≤T(⌈n/5⌉)+T(7n/10+6)+O(n)T(n) \le T(\lceil n/5 \rceil) + T(7n/10 + 6) + O(n) is linear because 15+710<1\tfrac15 + \tfrac{7}{10} < 1; groups of 3 give fractions summing to 1 and Θ(nlog⁡n)\Theta(n \log n), while groups of 7 or 9 work.
  • An adversary that splits fresh pairs across the median forces 32(n−1)\tfrac32(n - 1) comparisons; the best known bounds for the median are (2+ε)n(2 + \varepsilon)n below and 2.95n2.95n above, a gap open for over two decades.
  • In practice median of medians is a fallback (introselect): quickselect is faster on average, and random sampling needs only 1.5n+o(n)1.5n + o(n) expected comparisons for the median.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why is the plain algorithm with groups of 3 not linear?

  1. A group of 3 has no median
  2. It needs more comparisons per group than groups of 5 do
  3. The recursion on the medians would never terminate
  4. It guarantees only about n/3n/3 elements on each side, so T(n)≤T(n/3)+T(2n/3)+O(n)T(n) \le T(n/3) + T(2n/3) + O(n), whose fractions sum to 1: every level of the recursion costs Θ(n)\Theta(n), and there are Θ(log⁡n)\Theta(\log n) levels
Show the answer

D. It guarantees only about n/3n/3 elements on each side, so T(n)≤T(n/3)+T(2n/3)+O(n)T(n) \le T(n/3) + T(2n/3) + O(n), whose fractions sum to 1: every level of the recursion costs Θ(n)\Theta(n), and there are Θ(log⁡n)\Theta(\log n) levels

With groups of 3, half of the groups give 2 elements each above the pivot: 2⋅n/6=n/32 \cdot n/6 = n/3. The two recursive calls then cover n/3+2n/3=nn/3 + 2n/3 = n elements in total, the work no longer shrinks from level to level, and the recurrence solves to Θ(nlog⁡n)\Theta(n \log n).

Question 2

For n=1000n = 1000 distinct keys, at least how many keys does the bound 3n/10−63n/10 - 6 guarantee on each side of the median of medians?

  1. 300
  2. 294
  3. 500
  4. 100
Show the answer

B. 294

3⋅1000/10−6=2943 \cdot 1000/10 - 6 = 294. The −6-6 pays for two groups that may contribute fewer than 3 elements: the pivot's own group and a final partial group. So each recursive call keeps at most 1000−294=7061000 - 294 = 706 keys.

Question 3

Which statement about the number of comparisons needed to find the median of nn distinct keys is true?

  1. The exact worst-case constant is known to be 2
  2. Every deterministic algorithm needs at least (2+ε)n(2 + \varepsilon)n comparisons in the worst case for some tiny ε>0\varepsilon > 0, the best known algorithm needs about 2.95n2.95n, and randomized algorithms need only about 1.5n1.5n on average
  3. Median of medians is optimal: 5.43n5.43n comparisons are necessary
  4. Sorting is unavoidable, so Ω(nlog⁡n)\Omega(n \log n) comparisons are needed
Show the answer

B. Every deterministic algorithm needs at least (2+ε)n(2 + \varepsilon)n comparisons in the worst case for some tiny ε>0\varepsilon > 0, the best known algorithm needs about 2.95n2.95n, and randomized algorithms need only about 1.5n1.5n on average

Bent and John (1985) proved 2n−o(n)2n - o(n), Dor and Zwick raised it to (2+ε)n(2 + \varepsilon)n (2001), and their 1999 algorithm uses at most 2.95n2.95n. Floyd and Rivest's sampling algorithm uses 1.5n+o(n)1.5n + o(n) comparisons on average for the median, below the deterministic worst-case lower bound.

Question 4

In the 32(n−1)\tfrac32(n - 1) lower-bound argument, what does the adversary answer when the algorithm compares two keys that have never been compared before?

  1. It answers at random
  2. It reveals which key is the median
  3. It declares one key larger, places it above the median and the other below, so the comparison is crucial for neither key
  4. It places both keys above the median
Show the answer

C. It declares one key larger, places it above the median and the other below, so the comparison is crucial for neither key

Once one key is fixed above the median and the other below it, the comparison links neither of them to the median, so it is wasted for the algorithm. The adversary forces at least (n−1)/2(n - 1)/2 such wasted comparisons before one side fills up, on top of the n−1n - 1 crucial comparisons every algorithm needs.

Further reading

  • M. Blum, R. W. Floyd, V. Pratt, R. L. Rivest & R. E. Tarjan, "Time bounds for selection," Journal of Computer and System Sciences 7(4) (1973), 448–461.
  • A. Schönhage, M. Paterson & N. Pippenger, "Finding the median," Journal of Computer and System Sciences 13 (1976), 184–199.
  • S. W. Bent & J. W. John, "Finding the median requires 2n comparisons," Proceedings of the 17th ACM Symposium on Theory of Computing (1985), 213–216.
  • D. Dor & U. Zwick, "Selecting the median," SIAM Journal on Computing 28(5) (1999).
  • K. Chen & A. Dumitrescu, "Select with groups of 3 or 4," Algorithms and Data Structures (WADS 2015), LNCS 9214 (2015), 189–199.