Sub topic 9
Median of Medians: Guaranteed Linear Time
This chapter assumes you already know three things from earlier chapters. You know how the list-building version of quickselect splits items into lows, pivots, and highs. You know why a bad pivot sequence makes quickselect run in O(n^2). You can read a recurrence such as T(n) = T(n/2) + O(n) and recognize that it solves to O(n). Here we remove the worst case completely. The algorithm is called median of medians, also known as BFPRT after its inventors Blum, Floyd, Pratt, Rivest, and Tarjan (1973). It picks a pivot that is never terrible, and that one guarantee makes selection run in worst-case O(n).
The Problem Median of Medians Solves
Randomized quickselect is fast on average, but its running time depends on luck. Deterministic pivot rules such as "first element" or "median-of-three" can be beaten by inputs built to defeat them. If you need a hard upper bound, because the input may come from an adversary or because you have a real-time deadline, expected O(n) is not enough.
The ideal pivot would be the true median, since it splits the input exactly in half. Finding the median is the selection problem we are trying to solve, so we cannot get it cheaply. Median of medians aims lower. It finds an approximate median, a value that is guaranteed to have at least about 30% of the elements on each side of it. A split that is always at worst 30/70 is good enough to make the total work linear.
The Algorithm Step by Step
The procedure for selecting the k-th smallest element (0-based) of a list of n items is:
- If n is small (5 or fewer), sort it and return the element at index k.
- Split the items into groups of 5. The last group may have fewer.
- Find the median of each group by sorting it. Sorting 5 items takes constant time.
- Recursively call the selection algorithm on the list of group medians to find their median. This value is the pivot.
- Partition the items into
lows,pivots, andhighsaround that pivot. - Recurse into the one side that contains index k, as in ordinary quickselect.
Only step 4 differs from quickselect. The algorithm calls itself to choose the pivot, and then calls itself again to finish the search.
Here is the implementation:
def select_mom(items, k):
"""Deterministic worst-case O(n) selection (0-based k) using median of medians."""
if len(items) <= 5:
return sorted(items)[k]
chunks = [items[i:i + 5] for i in range(0, len(items), 5)]
medians = [sorted(c)[len(c) // 2] for c in chunks]
pivot = select_mom(medians, len(medians) // 2)
lows = [x for x in items if x < pivot]
pivots = [x for x in items if x == pivot]
highs = [x for x in items if x > pivot]
if k < len(lows):
return select_mom(lows, k)
if k < len(lows) + len(pivots):
return pivot
return select_mom(highs, k - len(lows) - len(pivots))
print(select_mom(list(range(100, 0, -1)), 10)) # 11The test input is 100 down to 1 in descending order. The element at 0-based index 10 in sorted order is 11. A first-element-pivot quickselect would take quadratic time on this reverse-sorted input. Median of medians takes linear time on it, as it does on every input.
Why the Pivot Is Always Good Enough
A worked example with 25 items
Picture the 25 items arranged as 5 groups, with each group sorted and the groups ordered by their medians. The rows below are groups. The middle column holds each group's median.
| Group | Smallest | 2nd | Median | 4th | Largest |
|---|---|---|---|---|---|
| G1 | 1 | 4 | 7 | 30 | 40 |
| G2 | 2 | 5 | 10 | 31 | 41 |
| G3 | 3 | 6 | **12** | 32 | 42 |
| G4 | 8 | 9 | 20 | 33 | 43 |
| G5 | 11 | 13 | 25 | 34 | 44 |
The medians are 7, 10, 12, 20, 25, so the median of medians is 12. Look at what we know for certain without comparing anything else:
- G1, G2, and G3 have medians of 12 or less. In each of those groups, the median and the two items below it are also at most 12. That gives 3 × 3 = 9 items guaranteed to be ≤ 12: {1, 4, 7, 2, 5, 10, 3, 6, 12}.
- By the same reasoning, G3, G4, and G5 contribute 9 items guaranteed to be ≥ 12: {12, 32, 42, 20, 33, 43, 25, 34, 44}.
So no matter how the other values are arranged, at most 25 − 9 = 16 items can end up strictly on either side of the pivot. The pivot cannot be among the few smallest or the few largest values.
The general bound
With n items there are ⌈n/5⌉ groups. At least half of the groups have a median ≤ the pivot. Each of those groups contributes 3 elements ≤ the pivot, with two possible exceptions: the partial last group, and the pivot's own group, which we count conservatively. The standard count (as in CLRS) gives:
- At least 3(⌈⌈n/5⌉/2⌉ − 2) ≥ 3n/10 − 6 elements are ≥ the pivot.
- Symmetrically, at least 3n/10 − 6 elements are ≤ the pivot.
So lows and highs each have at most 7n/10 + 6 elements. This holds for every input, including adversarial ones.
Duplicates do not break the bound
The code partitions three ways, using <, ==, and >. Elements equal to the pivot go into pivots and are never recursed into. The counting argument bounds the number of elements ≤ the pivot and the number ≥ the pivot, so it can only become more favorable when duplicates move into the middle group. A two-way partition that sends equal keys to one side would break this. With an input of all-equal values, one side would receive almost everything.
Solving the Recurrence
Each call does linear work: it forms groups, sorts them, and partitions. It also makes two recursive calls, one on about n/5 medians and one on at most 7n/10 + 6 elements:
T(n) ≤ T(⌈n/5⌉) + T(7n/10 + 6) + an
The key fact is that the two fractions add up to less than 1:
1/5 + 7/10 = 9/10
Intuitively, each level of recursion handles at most 90% of the previous level's total size. The work therefore forms a geometric series:
an + (9/10)an + (9/10)²an + … ≤ 10an
To check this formally, guess T(n) ≤ cn and substitute:
T(n) ≤ c(n/5 + 1) + c(7n/10 + 6) + an = (9/10)cn + 7c + an
This is ≤ cn whenever cn/10 − 7c ≥ an. That holds for all n ≥ 140 if c ≥ 20a. Smaller n are covered by a constant. So T(n) = O(n) in the worst case.
Why groups of 5?
The group size controls both fractions. With groups of size g (odd), you recurse on about n/g medians, and the guaranteed discard is about half of the groups times (g+1)/2 elements each.
| Group size | Pivot-finding call | Worst remaining side | Sum of fractions | Result |
|---|---|---|---|---|
| 3 | n/3 | 2n/3 | 1 | O(n log n) |
| 5 | n/5 | 7n/10 | 9/10 | O(n) |
| 7 | n/7 | 5n/7 | 6/7 | O(n) |
| 9 | n/9 | 13n/18 | 15/18 | O(n) |
With groups of 3 the fractions sum to exactly 1. The recurrence T(n) = T(n/3) + T(2n/3) + O(n) is the same shape as merge sort's, and it solves to O(n log n). Five is the smallest odd size that gives linear time. Larger groups also work, but each group costs more to sort, so 5 is the usual choice.
The Cost of the Guarantee
The 10an bound above is a real constant. Every level does the partitioning pass, sorts all the 5-element groups, and builds new lists, and the recursion multiplies this by up to 10. Randomized quickselect needs about 3.4n comparisons on average to find a median, and it does no group sorting. In practice median of medians is usually several times slower.
You can measure the difference by counting how many elements each version touches. The script below counts the total length of all lists passed into recursive calls. This undercounts median of medians, because it ignores the cost of sorting each group, but it is enough to show the trend.
import random
def mom_work(items, k, stats):
stats["work"] += len(items)
if len(items) <= 5:
return sorted(items)[k]
chunks = [items[i:i + 5] for i in range(0, len(items), 5)]
medians = [sorted(c)[len(c) // 2] for c in chunks]
pivot = mom_work(medians, len(medians) // 2, stats)
lows = [x for x in items if x < pivot]
pivots = [x for x in items if x == pivot]
highs = [x for x in items if x > pivot]
if k < len(lows):
return mom_work(lows, k, stats)
if k < len(lows) + len(pivots):
return pivot
return mom_work(highs, k - len(lows) - len(pivots), stats)
def rand_work(items, k, stats):
stats["work"] += len(items)
pivot = random.choice(items)
lows = [x for x in items if x < pivot]
pivots = [x for x in items if x == pivot]
highs = [x for x in items if x > pivot]
if k < len(lows):
return rand_work(lows, k, stats)
if k < len(lows) + len(pivots):
return pivot
return rand_work(highs, k - len(lows) - len(pivots), stats)
for n in (1_000, 10_000, 100_000):
data = list(range(n))
random.shuffle(data)
k = n // 2
s_mom, s_rand = {"work": 0}, {"work": 0}
assert mom_work(data, k, s_mom) == k
assert rand_work(data, k, s_rand) == k
print(f"n={n:>7} mom work/n={s_mom['work'] / n:.2f} random work/n={s_rand['work'] / n:.2f}")When you run it, both ratios stay roughly flat as n grows, which is what linear time looks like. The median-of-medians ratio is consistently higher. The random version's ratio also varies from run to run, while the median-of-medians ratio does not, because it is deterministic.
When to Use It and When Not To
Median of medians on its own is rarely the fastest choice. Its real uses are narrower:
- Fallback for hybrid algorithms. Start with fast quickselect, and switch to median of medians only if progress stalls. The next chapter covers this approach, called introselect. It is how libraries keep quickselect's average speed and still bound the worst case.
- Adversarial or untrusted input. If an attacker can choose the input and you cannot rely on a hidden random seed, a deterministic linear bound protects against crafted slow cases.
- Guaranteed quicksort pivots. Using median of medians to pick quicksort's pivot gives worst-case O(n log n) sorting. It is slower in practice than heapsort-based fallbacks, so it is mostly of theoretical interest.
- Proofs and teaching. It shows that selection is fundamentally a linear-time problem, unlike sorting, which needs Ω(n log n) comparisons.
Common mistakes
- Recursing only on the medians to get the answer. The median of medians is a pivot, not the answer. You still have to partition and continue.
- Finding the median of medians by sorting the medians. That costs O((n/5) log(n/5)) and destroys the linear bound. The pivot must be found with a recursive selection call.
- Using groups of 3. As the table shows, this gives O(n log n).
- Two-way partitioning with duplicates. Equal keys must be kept out of the recursive call, or the 70% bound fails.
- Off-by-one in the medians index. Use
len(medians) // 2as a 0-based index. For an even count this picks the upper middle element, and the bound still holds.
Exercise
Explain why using groups of 3 gives O(n log n) instead of O(n). Write the recurrence and say which fractions sum to what.
Show answer
With groups of 3, the pivot-finding call works on about n/3 medians. At least half the groups contribute 2 elements on each side of the pivot, so about n/3 elements are guaranteed to be discarded and the remaining side can hold about 2n/3. The recurrence is T(n) = T(n/3) + T(2n/3) + O(n). The fractions sum to 1/3 + 2/3 = 1, so every level of recursion still does about n total work, and there are O(log n) levels. That gives O(n log n). Groups of 5 give 1/5 + 7/10 = 9/10 < 1, so the per-level work shrinks geometrically and the total is O(n).
Exercise
For n = 1000 distinct elements, use the bound 3n/10 − 6 to give the largest possible size of the side that median of medians recurses into. Then compare it with the worst case for first-element-pivot quickselect.
Show answer
At least 3(1000)/10 − 6 = 294 elements lie on each side of the pivot, counting the pivot. The side you recurse into therefore has at most 1000 − 294 = 706 elements, which matches 7n/10 + 6 = 706. First-element-pivot quickselect on sorted input can recurse into 999 elements, discarding only one element per step. That is why it degrades to O(n^2).
Exercise
Modify select_mom to use groups of 7. Which two lines change, and is the result still linear?
Show answer
Change the chunking line to chunks = [items[i:i + 7] for i in range(0, len(items), 7)] and the base case to if len(items) <= 7. The medians line, sorted(c)[len(c) // 2], already works for any group size. The result is still linear: the recurrence is about T(n/7) + T(5n/7) + O(n), and 1/7 + 5/7 = 6/7 < 1. Each group costs more to sort, but there are fewer of them.