Medians & order statistics
◈ 5 cardsBinary 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.