Memra

Medians & order statistics

◈ 5 cards

Binary search as a warm-up; RANDOMIZED-SELECT expected Θ(n) via one-sided recursion; median-of-medians SELECT worst-case Θ(n) with groups of 5.

Finding the -th smallest without sorting

The -th order statistic is the -th smallest element; is the minimum, the maximum, the (lower) median. Sorting then indexing costs — but the selection problem can be solved in . You don't need the whole order, only which side of a pivot the answer lies on.

Warm-up: binary search

On a sorted array, binary search finds a target in by halving the live range each step — "one-sided linear search." It's the prototype for the idea behind selection: identify which half contains the answer and discard the other.

RANDOMIZED-SELECT — expected

This is one-sided quicksort. Call RANDOMIZED-PARTITION to get a random pivot at rank within the current range. If , return the pivot. If , recurse only on the low side; if , recurse only on the high side (adjusting ). Recursing on one side is the whole difference from quicksort: it turns a harmonic-sum into a geometric sum. A partition is "helpful" (cuts the range to ) with probability , so expected work is . Worst case is but, as in quicksort, only with negligible probability.

SELECT (median-of-medians) — worst-case

To kill even the unlikely worst case, choose a provably good pivot. (1) Split into groups of 5; (2) insertion-sort each group; (3) take each group's median; (4) recursively SELECT the median of those medians; (5) partition around and recurse on the right side. guarantees at least elements on each side are eliminated, so the recursive call has elements. The recurrence solves to because .

Worked example

Binary search for in returns index ; searching for the absent returns . On , RANDOMIZED-SELECT returns the rd smallest , the st , and the th . The runnable exercise implements both and reproduces these.

012345A710432015pivotq = 4710431520keep — rank 3 < 5dropq = 0310471520dropkeepq = 23471015203rd smallestOne side is dropped at every step.
One-sided recursion. Each partition places one element and throws away a whole side, so the work is a shrinking geometric series rather than quicksort’s harmonic one.
G13581217G21691421G324111619Medians 8, 9, 11 → x = 9.
Step 1 of SELECT: groups of 5, each insertion-sorted so its median sits in the centre column. The pivot x = 9 is the median of those three medians, which is what forces at least 3n/10 elements out on each side.
NORMAL ~/memra/learn/comp-372/medians-and-order-statistics utf-8 LF