3.6.10Sorting & Searching

Linear time selection — median of medians algorithm

2,222 words10 min readdifficulty · medium

WHAT are we even solving?

WHY not just sort? Sorting gives all order statistics but costs O(nlogn)O(n\log n). We only need one. Doing more work than necessary is the thing 80/20 tells us to avoid — so we aim for O(n)O(n).


HOW Quickselect works (the foundation)

Quickselect = Quicksort that only recurses into the side containing kk.

  1. Pick a pivot pp.
  2. Partition AA around pp: smaller elements left, larger right. Pivot lands at its final sorted index ii.
  3. If i=ki = k → done. If k<ik < i → recurse left. If k>ik > i → recurse right (adjust kk).

The trick: Median of Medians chooses the pivot

WHY 5? It's the smallest odd group size for which the recursion math closes (gives linear time). We'll see exactly where 5 comes from in the derivation. (Groups of 3 fail; 7 also works but 5 is optimal in practice.)

Figure — Linear time selection — median of medians algorithm

WHY this pivot is provably good (the heart)

Let MM be the median of the n/5\lceil n/5\rceil group-medians. We bound how many elements are guaranteed smaller than MM (and by symmetry, larger).

By symmetry, at least 3n10\frac{3n}{10} elements are M\ge M. Therefore the larger side of the partition has at most n3n10=7n10n - \frac{3n}{10} = \frac{7n}{10} elements.


Worked example 1 — finding the pivot MM

Array (n=15): [12, 3, 5, 7, 19, 1, 8, 22, 4, 6, 15, 9, 2, 11, 17], want k=8k=8 (the median).

Step 1 — groups of 5. [12,3,5,7,19] [1,8,22,4,6] [15,9,2,11,17] Why? Constant-size groups make per-group median trivial.

Step 2 — medians of each group (sort the 5, take middle):

  • [3,5,7,12,19]7
  • [1,4,6,8,22]6
  • [2,9,11,15,17]11

Step 3 — median of medians of [7,6,11]7. So pivot M=7M=7. Why this matters: 7 is guaranteed not to be near an extreme, so partitioning around it removes a constant fraction.

Step 4 — partition around 7: elements <7<7: [3,5,1,4,6,2] (6 of them) → 7 lands at index 7 (1-indexed). Since k=8>7k=8>7, recurse right into [12,19,8,22,15,9,11,17] for the (87)=1(8-7)=1st smallest = 8. ✅ (8 is indeed the median of the original.)


Worked example 2 — why a bad pivot would hurt (steel-man)

Same array, but suppose we pick pivot = 1 (the min).

Partition: nothing on the left, 1 lands at index 1. We must recurse into the remaining 14 elements. We removed only one element for O(n)O(n) work.

Why this step shows the danger: if every pivot were a min/max, we'd do O(n)+O(n1)+=O(n2)O(n)+O(n-1)+\dots=O(n^2). MoM forbids this because MM always has 3n10\ge \frac{3n}{10} elements on each side.


Common mistakes (Steel-man them)


Forecast-then-Verify


Pseudocode (self-contained)

Select(A, k):
    if len(A) <= 5:
        return sorted(A)[k-1]
    medians = [median(group) for group in chunks(A, 5)]
    M = Select(medians, ceil(len(medians)/2))      # median of medians
    L = [x for x in A if x < M]
    E = [x for x in A if x == M]
    G = [x for x in A if x > M]
    if k <= len(L):           return Select(L, k)
    elif k <= len(L)+len(E):  return M
    else:                     return Select(G, k - len(L) - len(E))

Why the 3-way split (L, E, G)? It safely handles duplicates of MM so we never recurse on a side that can't shrink.


Flashcards

What problem does selection solve?
Finding the kk-th smallest element (k-th order statistic) without fully sorting.
Why can plain Quickselect be O(n2)O(n^2)?
A consistently bad pivot (min/max) removes only one element per call.
What is the median-of-medians pivot rule?
Split into groups of 5, take each group's median, recursively select the median of those medians as the pivot.
How many elements are guaranteed M\le M (the MoM pivot)?
At least 3n/103n/10 (3 per group in about half of the n/5n/5 groups).
What is the MoM recurrence?
T(n)T(n/5)+T(7n/10)+cnT(n)\le T(n/5)+T(7n/10)+cn.
Why does that recurrence give O(n)O(n)?
Because 1/5+7/10=9/10<11/5+7/10 = 9/10 < 1; substituting T(n)anT(n)\le an needs a10ca\ge 10c, so T(n)=O(n)T(n)=O(n).
Why does group size 3 fail?
Guarantee drops to n/3n/3 per side; recurrence sums 1/3+2/3=11/3+2/3=1, not <1<1, so it isn't linear.
Why use MoM over random pivots in practice?
Only for guaranteed worst-case O(n)O(n); random is faster on average but O(n2)O(n^2) worst case.
Why the 3-way (L,E,G) partition?
To correctly handle duplicates of the pivot and ensure the recursive side always shrinks.
Which fraction inequality is the crux of linearity?
Sum of recursive-size fractions must be strictly less than 1.

Recall Feynman: explain to a 12-year-old

Imagine 15 kids and you want the kid of middle height — but lining everyone up takes forever. Trick: split kids into little teams of 5. In each team, find the middle-height kid. Now look only at those middle kids and find their middle kid. That kid is a "pretty middle" kid — never the shortest or tallest. Stand everyone shorter on the left, taller on the right. Whichever side has the kid you want, repeat the game there. Because each round throws away a big chunk of kids, you finish super fast — and the trick guarantees you never get unlucky.

Connections

  • Quickselect — MoM is the pivot-choosing upgrade that makes it worst-case linear.
  • Quicksort — same partition machinery; MoM pivot gives worst-case O(nlogn)O(n\log n) quicksort.
  • Order statistics — median, min, max are special cases of selection.
  • Master Theorem / Recurrence relations — but note MoM needs substitution, not the Master Theorem (unequal subproblems).
  • Randomized algorithms — contrast: expected vs worst-case guarantees.
  • Partitioning (Lomuto vs Hoare) — the engine behind step 4.

Concept Map

solved without sorting

too much work

recurse one side

good pivot

bad pivot min/max

guarantees good pivot

split into

median each group

recursive Select

at least 3n/10 smaller and larger

closes recurrence

solves to

Selection Problem k-th smallest

Quickselect

Full Sort O n log n

Pivot Choice

T n equals T n/2 plus O n gives O n

T n-1 plus O n gives O n squared

Median of Medians

Groups of 5

Group Medians

Median M as pivot

Larger side leq 7n/10

T n equals T n/5 plus T 7n/10 plus O n

O n worst-case

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, problem simple hai: ek unsorted array me kk-th sabse chhota element nikalna hai, lekin pura array sort nahi karna (kyunki sort O(nlogn)O(n\log n) leta hai, aur humein sirf ek element chahiye). Quickselect isko average me O(n)O(n) me kar deta hai, par agar pivot har baar bekaar (min ya max) chun liya, toh worst case O(n2)O(n^2) ho jata hai. Yahi galti se bachne ke liye Median of Medians trick aata hai.

Trick ye hai: array ko 5-5 ke groups me baanto, har group ka median nikaalo (5 elements ka median nikalna constant kaam hai), phir un saare medians ka median recursively nikaalo — usko pivot MM bana lo. Magic ye hai ki MM kabhi bhi bahut chhota ya bahut bada nahi ho sakta: kam se kam 3n/103n/10 elements MM se chhote aur 3n/103n/10 bade guaranteed hote hain. Matlab partition ke baad bachi hui side 7n/107n/10 se zyada nahi hoti.

Isi guarantee se recurrence banta hai T(n)T(n/5)+T(7n/10)+cnT(n) \le T(n/5) + T(7n/10) + cn. Yahan sabse important baat: 15+710=910\frac15 + \frac{7}{10} = \frac{9}{10}, jo 11 se kam hai — isi wajah se recursion linear me collapse ho jaata hai aur answer O(n)O(n) aata hai. Agar group size 3 lo toh fractions 13+23=1\frac13+\frac23=1 ban jaate hain, aur linear nahi rehta — isiliye 5 use karte hain.

Exam/interview ke liye yaad rakho: MoM ka asli faayda worst-case guarantee hai, practical speed nahi (constant factor bada hota hai). Real code me log randomized quickselect ya introselect use karte hain, par theory aur adversarial inputs ke liye MoM gold standard hai. "9/10 < 1" wali line hi pura concept hai — wahi 80/20 hai.

Go deeper — visual, from zero

Test yourself — Sorting & Searching

Connections