Sub topic 9
Median of Medians: Guaranteed Linear Time
This chapter assumes you already know quickselect's one-sided recursion, the three-group split into lows, pivots, and highs, and why a run of bad pivots pushes randomized quickselect to O(n^2). You should also be comfortable with recurrence relations at the level of "this sums to a geometric series."
Randomized quickselect is fast on average, but it offers no guarantee. An unlucky run of pivots, or an adversary who can predict them, can force quadratic time. Median of medians fixes this. It is a deterministic way to choose a pivot that always throws away a fixed fraction of the input, so selection runs in O(n) time even in the worst case. The algorithm was published in 1973 by Blum, Floyd, Pratt, Rivest, and Tarjan, and is often called BFPRT.
The Idea: A Pivot That Is Never Too Lopsided
Quickselect degrades when the pivot lands near one end of the data. Median of medians spends a little extra work to find a pivot that is guaranteed to sit somewhere in the middle. The pivot is not the exact median, but it is close enough.
The steps are:
- Split the input into groups of 5 elements. The last group may be smaller.
- Sort each group and take its median. Sorting 5 elements costs a constant amount of work.
- Recursively call the selection algorithm on the list of medians to find their median. This value is the pivot.
- Partition the full input around the pivot, then recurse into only the side that contains k, exactly as quickselect does.
Implementation
The version below builds new lists for clarity. It uses zero-based k, and it reuses the three-group split from earlier chapters, so duplicate values are handled correctly.
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)) # 11A reverse-sorted input like range(100, 0, -1) is the kind of input that breaks a first-element pivot. Here it causes no trouble.
Why the Pivot Is Good Enough
There are about n/5 group medians. The pivot is their median, so at least half of those medians, about n/10 of them, are greater than or equal to the pivot. Each of those medians belongs to a group in which at least 3 elements (the median and the two above it) are greater than or equal to the median, and therefore greater than or equal to the pivot. That gives at least about 3n/10 elements that are ≥ the pivot. The same argument shows at least about 3n/10 elements are ≤ the pivot.
So neither lows nor highs can hold more than about 7n/10 elements. The exact bound has a small additive constant, which does not affect the asymptotics.
The Recurrence
Each call does linear work (grouping, sorting groups, partitioning) plus two recursive calls:
- one on the n/5 medians to find the pivot
- one on at most 7n/10 elements after partitioning
That gives T(n) ≤ T(n/5) + T(7n/10) + cn.
The two subproblem sizes add up to n/5 + 7n/10 = 9n/10, which is less than n. Each level of recursion therefore does at most 9/10 of the previous level's total work. Summing gives cn(1 + 9/10 + 81/100 + …) = 10cn, which is O(n).
Why It Is Rarely Used Alone
Median of medians is linear, but its constant is large. Every call sorts many small groups, runs a full recursive selection just to pick the pivot, and then partitions. Random pivots usually discard close to half the input, while this method may keep up to 70%.
| Property | Randomized quickselect | Median of medians |
|---|---|---|
| Expected time | O(n) | O(n) |
| Worst-case time | O(n^2) | O(n) |
| Constant factor | Small | Several times larger |
| Deterministic | No | Yes |
In practice, randomized quickselect is faster on almost every input. Median of medians is used as a fallback that is only called in when quickselect is making too little progress. The next chapter covers that hybrid, called introselect.
Exercise
Explain why choosing groups of 3 instead of 5 makes median-of-medians selection O(n log n) instead of O(n).
Show answer
With groups of 3, the pivot is guaranteed to have about n/3 elements on each side, so a side can hold up to 2n/3 elements. The recurrence becomes T(n) ≤ T(n/3) + T(2n/3) + cn. Because 1/3 + 2/3 = 1, the total work does not shrink from one recursion level to the next. Each of the roughly log n levels costs about cn, for O(n log n) in total.
Exercise
For an input of 1,000 distinct elements, about how many elements are guaranteed to be eliminated after partitioning around the median-of-medians pivot, and what is the largest size the recursive call can have?
Show answer
There are 200 groups and 200 medians. At least about 100 of those medians are at least as large as the pivot, and each brings 3 elements that are ≥ the pivot, so at least about 300 elements are on the high side. By symmetry, at least about 300 are on the low side. Whichever side the recursion enters, at least about 300 elements are eliminated, so the recursive call works on at most about 700 elements (7n/10).