TExcelTAD
Home › Sorting & Order Statistics › Median of Medians: Selection in Worst-Case Linear Time

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 Θ(n2)\Theta(n^2). In 1973 Blum, Floyd, Pratt, Rivest and Tarjan showed that selection can be done in O(n)O(n) 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 Ω(nlg⁡n)\Omega(n \lg n) comparisons (Decision Trees and the Comparison Lower Bound).

The algorithm

text
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 ⌈n/5⌉\lceil n/5 \rceil 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.

python · try it yourself
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++

cpp · try it yourself
#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 xx is the median of the middle row.

text
            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 xx contributes three values that are at least xx: its median and the two values below it (marked M and #, plus the corresponding three in xx's own column). There are g=⌈n/5⌉g = \lceil n/5 \rceil columns, and at least half of them, ⌈g/2⌉\lceil g/2 \rceil, have a median at least xx. Discount xx's own column and the last column, which may have fewer than five values: at least

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

values are greater than xx. By the same argument at least 3n10−6\frac{3n}{10} - 6 values are less than xx. So each side of the partition, LL or GG, has at most n−(3n10−6)=7n10+6n - \left(\frac{3n}{10} - 6\right) = \frac{7n}{10} + 6 values.

The program measures where the pivot actually lands, as a fraction of nn, on several kinds of input. It never leaves the window from 30 to 70 percent.

python · try it yourself
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 T(n)T(n) be the worst-case running time. Lines 2, 3 and 5 take O(n)O(n): sorting a group of five is a constant amount of work. Line 4 is a call on ⌈n/5⌉\lceil n/5 \rceil values, and lines 6 or 8 a call on at most 7n10+6\frac{7n}{10} + 6. So, for nn above some constant,

T(n)≤T(⌈n5⌉)+T(7n10+6)+cn.T(n) \le T\left(\left\lceil \frac{n}{5} \right\rceil\right) + T\left(\frac{7n}{10} + 6\right) + cn.

The key fact is 15+710=910<1\frac{1}{5} + \frac{7}{10} = \frac{9}{10} < 1: the two subproblems together are a constant fraction smaller than the problem. In the recursion tree (Recursion Trees) the level costs then shrink geometrically, cn,910cn,(910)2cn,…cn, \frac{9}{10} cn, \left(\frac{9}{10}\right)^2 cn, \ldots, and sum to at most 10cn10cn. The master theorem does not apply to two subproblems of different sizes, so here is the proof by substitution.

Claim. T(n)≤dnT(n) \le dn for a suitable constant dd and all n≥1n \ge 1.

T(n)≤d⌈n5⌉+d(7n10+6)+cninduction hypothesis≤d(n5+1)+7dn10+6d+cn⌈y⌉≤y+1=9dn10+7d+cn=dn−(dn10−7d−cn)\begin{aligned} T(n) &\le d \left\lceil \frac{n}{5} \right\rceil + d \left(\frac{7n}{10} + 6\right) + cn && \text{induction hypothesis} \\ &\le d\left(\frac{n}{5} + 1\right) + \frac{7dn}{10} + 6d + cn && \lceil y \rceil \le y + 1 \\ &= \frac{9dn}{10} + 7d + cn \\ &= dn - \left(\frac{dn}{10} - 7d - cn\right) \end{aligned}

The bracket is non-negative when dn10−7d≥cn\frac{dn}{10} - 7d \ge cn, which holds for example when n≥140n \ge 140 and d≥20cd \ge 20c: then dn10−7d≥dn10−dn20=dn20≥cn\frac{dn}{10} - 7d \ge \frac{dn}{10} - \frac{dn}{20} = \frac{dn}{20} \ge cn. Choosing dd large enough also covers all n<140n < 140 as base cases. So T(n)=O(n)T(n) = O(n), and since reading the input takes Ω(n)\Omega(n), T(n)=Θ(n)T(n) = \Theta(n).

Why groups of five?

Groups of seven work too: each side then has at most about 5n7\frac{5n}{7} values, and 17+57=67<1\frac{1}{7} + \frac{5}{7} = \frac{6}{7} < 1. Groups of three do not: the guarantee drops to about n3\frac{n}{3} on each side, so the subproblems have sizes n3\frac{n}{3} and 2n3\frac{2n}{3}, which add up to nn. The recurrence T(n)=T(n/3)+T(2n/3)+cnT(n) = T(n/3) + T(2n/3) + cn has Θ(n)\Theta(n) work on every level for about log⁡3/2n\log_{3/2} n levels, so it solves to Θ(nlg⁡n)\Theta(n \lg n), no better than sorting. The program counts comparisons (in the insertion sorts and in the partition) for the three group sizes.

python · try it yourself
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 nn quadruples: that is the extra lg⁡n\lg n factor, with a small constant. Notice too how large the constants are compared with randomized quickselect's 3.39n3.39n; 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 xx?

  1. about n/2n/2
  2. about 3n/103n/10 (precisely at least 3n10−6\frac{3n}{10} - 6)
  3. about n/5n/5
  4. none are guaranteed

Why does the recurrence T(n)≤T(n/5)+T(7n/10)+cnT(n) \le T(n/5) + T(7n/10) + cn solve to O(n)O(n)?

  1. Because of case 1 of the master theorem
  2. Because 15+710<1\frac{1}{5} + \frac{7}{10} < 1, so the level costs of the recursion tree shrink geometrically
  3. Because each call is on half the input
  4. Because the recursion has constant depth

What goes wrong with groups of three?

  1. The medians are not defined
  2. The subproblems have sizes about n/3n/3 and 2n/32n/3, which add up to nn, so the recurrence gives Θ(nlg⁡n)\Theta(n \lg n)
  3. The algorithm becomes incorrect
  4. It becomes quadratic

Which statement is true of median of medians compared with randomized quickselect?

  1. It is faster on typical inputs
  2. It is linear in the worst case, but with a much larger constant, so practical code uses it mainly as a fallback
  3. It needs random numbers
  4. It sorts the array as a side effect