Median of Medians: Selection in Worst-Case Linear Time
Randomized quickselect finds any order statistic in expected linear time, but an unlucky run can still take . In 1973 Blum, Floyd, Pratt, Rivest and Tarjan showed that selection can be done in time in the worst case, with no randomness at all. Their algorithm is quickselect with a pivot that is guaranteed to be good: it splits the input into groups of five, takes the median of each group, and recursively finds the median of those medians. That pivot is never in the bottom or top 30 percent, and that is enough to make the total linear.
The algorithm is rarely the fastest in practice, because its constant is large. Its importance is the theorem: selection is genuinely easier than sorting, which needs comparisons (Decision Trees and the Comparison Lower Bound).
The algorithm
SELECT(a, k) // the k-th smallest of a, 1 <= k <= n
1 if n <= 10: sort a by insertion sort and return a[k - 1]
2 split a into groups of 5 (the last group may be smaller)
3 sort each group by insertion sort; let M be the list of the group medians
4 x = SELECT(M, ceil(|M| / 2)) // the median of the medians, found recursively
5 L = values of a less than x, E = values equal to x, G = values greater than x
6 if k <= |L|: return SELECT(L, k)
7 else if k <= |L| + |E|: return x
8 else: return SELECT(G, k - |L| - |E|)There are two recursive calls: one on the medians to choose the pivot (line 4), and one on a single side of the partition (lines 6 or 8), as in quickselect. Line 5 partitions around a value; keeping the equal values apart makes the algorithm correct with duplicates too.
def insertion_sorted(g):
g = list(g)
for i in range(1, len(g)):
key, j = g[i], i - 1
while j >= 0 and g[j] > key:
g[j + 1] = g[j]; j -= 1
g[j + 1] = key
return g
def select(a, k, depth=0, trace=False):
pad = " " * depth
if len(a) <= 10:
return insertion_sorted(a)[k - 1]
groups = [a[i:i + 5] for i in range(0, len(a), 5)]
medians = [insertion_sorted(g)[(len(g) - 1) // 2] for g in groups]
x = select(medians, (len(medians) + 1) // 2, depth + 1)
L = [v for v in a if v < x]
E = [v for v in a if v == x]
G = [v for v in a if v > x]
if trace:
print(f"{pad}n = {len(a)}: {len(groups)} groups, medians {medians}")
print(f"{pad}pivot {x}: {len(L)} smaller, {len(G)} larger; looking for rank {k}")
if k <= len(L):
return select(L, k, depth + 1, trace)
if k <= len(L) + len(E):
return x
return select(G, k - len(L) - len(E), depth + 1, trace)
a = [31, 74, 8, 52, 19, 66, 3, 90, 45, 27, 58, 12, 81, 36, 70, 5, 49, 23, 95, 61, 14, 40, 86, 29, 77]
print("median:", select(a, 13, trace=True))
print("check: ", sorted(a)[12])n = 25: 5 groups, medians [31, 45, 58, 49, 40]
pivot 45: 12 smaller, 12 larger; looking for rank 13
median: 45
check: 45
The pivot came from the five group medians, and it left 12 values on one side and 12 on the other: as good a split as possible. The guarantee below says it can never be worse than about 30 to 70.
In C++
#include <algorithm>
#include <cstdio>
#include <vector>
long long comparisons = 0;
void insertion_sort(std::vector<int>& g) {
for (std::size_t i = 1; i < g.size(); ++i) {
int key = g[i];
std::size_t j = i;
while (j > 0 && (++comparisons, g[j - 1] > key)) { g[j] = g[j - 1]; --j; }
g[j] = key;
}
}
int select(std::vector<int> a, int k) { // k-th smallest, 1-based
if (a.size() <= 10) { insertion_sort(a); return a[k - 1]; }
std::vector<int> medians;
for (std::size_t i = 0; i < a.size(); i += 5) {
std::vector<int> g(a.begin() + i, a.begin() + std::min(i + 5, a.size()));
insertion_sort(g);
medians.push_back(g[(g.size() - 1) / 2]);
}
int x = select(medians, (static_cast<int>(medians.size()) + 1) / 2);
std::vector<int> L, G;
int equal = 0;
for (int v : a) {
++comparisons;
if (v < x) { L.push_back(v); continue; }
++comparisons;
if (v > x) G.push_back(v); else ++equal;
}
if (k <= static_cast<int>(L.size())) return select(L, k);
if (k <= static_cast<int>(L.size()) + equal) return x;
return select(G, k - static_cast<int>(L.size()) - equal);
}
int main() {
std::vector<int> a = {31, 74, 8, 52, 19, 66, 3, 90, 45, 27, 58, 12, 81, 36, 70, 5, 49, 23, 95, 61, 14, 40, 86, 29, 77};
std::printf("median: %d\n", select(a, 13));
for (int n : {1000, 10000, 100000}) {
std::vector<int> v(n);
for (int i = 0; i < n; ++i) v[i] = i; // sorted: the worst case of naive quickselect
comparisons = 0;
int m = select(v, (n + 1) / 2);
std::printf("n = %6d: median %5d, %8lld comparisons = %.2f n\n", n, m, comparisons, static_cast<double>(comparisons) / n);
}
}median: 45
n = 1000: median 499, 6713 comparisons = 6.71 n
n = 10000: median 4999, 71856 comparisons = 7.19 n
n = 100000: median 49999, 743144 comparisons = 7.43 n
On sorted input, which makes the deterministic last-element quickselect quadratic, the comparisons per element creep up only slowly, towards a constant: the analysis below proves that they stay bounded.
Why the pivot is good
Picture the groups as columns, each sorted from top (small) to bottom (large), and the columns ordered by their medians. The pivot is the median of the middle row.
columns with median < x x's column columns with median > x
smaller . . . . . . . . . . . . .
. . . . . . . . . . . . .
medians m m m m m m x M M M M M M
. . . . . . . # # # # # #
larger . . . . . . . # # # # # #Every column whose median is at least contributes three values that are at least : its median and the two values below it (marked M and #, plus the corresponding three in 's own column). There are columns, and at least half of them, , have a median at least . Discount 's own column and the last column, which may have fewer than five values: at least
values are greater than . By the same argument at least values are less than . So each side of the partition, or , has at most values.
The program measures where the pivot actually lands, as a fraction of , on several kinds of input. It never leaves the window from 30 to 70 percent.
import random
def insertion_sorted(g):
g = list(g)
for i in range(1, len(g)):
key, j = g[i], i - 1
while j >= 0 and g[j] > key:
g[j + 1] = g[j]; j -= 1
g[j + 1] = key
return g
def select(a, k):
if len(a) <= 10:
return insertion_sorted(a)[k - 1]
medians = [insertion_sorted(a[i:i + 5])[(min(5, len(a) - i) - 1) // 2] for i in range(0, len(a), 5)]
x = select(medians, (len(medians) + 1) // 2)
L = [v for v in a if v < x]
E = sum(1 for v in a if v == x)
G = [v for v in a if v > x]
if k <= len(L): return select(L, k)
if k <= len(L) + E: return x
return select(G, k - len(L) - E)
def pivot_rank_fraction(a):
medians = [insertion_sorted(a[i:i + 5])[(min(5, len(a) - i) - 1) // 2] for i in range(0, len(a), 5)]
x = select(medians, (len(medians) + 1) // 2)
return sum(1 for v in a if v < x) / len(a)
rng = random.Random(17)
n = 2000
shapes = {
"random": rng.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"organ pipe": list(range(0, n, 2)) + list(range(n - 1, 0, -2)),
"small first": [v for i in range(0, n, 5) for v in (i // 5, i // 5 + 1000, i // 5 + 1001, i // 5 + 1002, i // 5 + 1003)][:n],
}
for name, a in shapes.items():
print(f"{name:>11}: pivot has {pivot_rank_fraction(a):.3f} n values below it")
print(f"guaranteed window: {(3 * n / 10 - 6) / n:.3f} to {(7 * n / 10 + 6) / n:.3f}") random: pivot has 0.506 n values below it
sorted: pivot has 0.498 n values below it
reversed: pivot has 0.498 n values below it
organ pipe: pivot has 0.497 n values below it
small first: pivot has 0.597 n values below it
guaranteed window: 0.297 to 0.703
The "small first" input puts one small value and four large ones in every group, so every group median is large; that pushes the pivot well away from the middle. Even then it stays inside the window.
The recurrence
Let be the worst-case running time. Lines 2, 3 and 5 take : sorting a group of five is a constant amount of work. Line 4 is a call on values, and lines 6 or 8 a call on at most . So, for above some constant,
The key fact is : the two subproblems together are a constant fraction smaller than the problem. In the recursion tree (Recursion Trees) the level costs then shrink geometrically, , and sum to at most . The master theorem does not apply to two subproblems of different sizes, so here is the proof by substitution.
Claim. for a suitable constant and all .
The bracket is non-negative when , which holds for example when and : then . Choosing large enough also covers all as base cases. So , and since reading the input takes , .
Why groups of five?
Groups of seven work too: each side then has at most about values, and . Groups of three do not: the guarantee drops to about on each side, so the subproblems have sizes and , which add up to . The recurrence has work on every level for about levels, so it solves to , no better than sorting. The program counts comparisons (in the insertion sorts and in the partition) for the three group sizes.
import random
count = 0
def insertion_sorted(g):
global count
g = list(g)
for i in range(1, len(g)):
key, j = g[i], i - 1
while j >= 0:
count += 1
if g[j] <= key: break
g[j + 1] = g[j]; j -= 1
g[j + 1] = key
return g
def select(a, k, q):
global count
if len(a) <= 2 * q:
return insertion_sorted(a)[k - 1]
medians = [insertion_sorted(a[i:i + q])[(min(q, len(a) - i) - 1) // 2] for i in range(0, len(a), q)]
x = select(medians, (len(medians) + 1) // 2, q)
L, G, E = [], [], 0
for v in a:
count += 1
if v < x: L.append(v); continue
count += 1
if v > x: G.append(v)
else: E += 1
if k <= len(L): return select(L, k, q)
if k <= len(L) + E: return x
return select(G, k - len(L) - E, q)
rng = random.Random(3)
sizes = [500, 2000, 8000, 32000]
data = {n: rng.sample(range(n), n) for n in sizes}
for q in [3, 5, 7]:
row = []
for n in sizes:
count = 0
assert select(data[n], (n + 1) // 2, q) == (n - 1) // 2
row.append(f"{count / n:5.2f}")
print(f"groups of {q}: comparisons / n at n = 500, 2000, 8000, 32000:", " ".join(row))groups of 3: comparisons / n at n = 500, 2000, 8000, 32000: 9.77 10.75 11.52 12.23
groups of 5: comparisons / n at n = 500, 2000, 8000, 32000: 8.78 9.40 9.64 9.79
groups of 7: comparisons / n at n = 500, 2000, 8000, 32000: 9.09 9.43 9.84 9.97
With groups of five the increases shrink quickly (0.62, then 0.24, then 0.15), and groups of seven behave alike: the ratio is approaching a constant of about 10 comparisons per element, the linear behaviour. With groups of three it keeps rising by roughly the same amount, about 0.7 to 1.0, every time quadruples: that is the extra factor, with a small constant. Notice too how large the constants are compared with randomized quickselect's ; this is why libraries use quickselect, often with median of medians only as a fallback when the recursion goes badly (introselect, the selection counterpart of introsort). C++'s std::nth_element is implemented this way in common standard libraries.
Test yourself
With groups of five, at least how many values are guaranteed to be greater than the median of medians ?
- about
- about (precisely at least )
- about
- none are guaranteed
Why does the recurrence solve to ?
- Because of case 1 of the master theorem
- Because , so the level costs of the recursion tree shrink geometrically
- Because each call is on half the input
- Because the recursion has constant depth
What goes wrong with groups of three?
- The medians are not defined
- The subproblems have sizes about and , which add up to , so the recurrence gives
- The algorithm becomes incorrect
- It becomes quadratic
Which statement is true of median of medians compared with randomized quickselect?
- It is faster on typical inputs
- It is linear in the worst case, but with a much larger constant, so practical code uses it mainly as a fallback
- It needs random numbers
- It sorts the array as a side effect