Medians and Order Statistics

Algorithms · Advanced Placement

Medians and Order Statistics: the big picture

The selection problem asks for the element of a given rank in an unordered collection, with the median the most important special case. Sorting and indexing solves it in linearithmic time, but selection is strictly easier and can be done in linear time. Minimum and maximum are found with n minus one comparisons each, and both together with about three halves n comparisons by processing elements in pairs, which is optimal. Randomized selection adapts quicksort: partition, and then recurse only into the side containing the desired rank, discarding the other. Because only one side is pursued, the expected running time satisfies a recurrence whose solution is linear rather than linearithmic, and the analysis uses the fact that a random pivot splits the array well with constant probability. The worst case remains quadratic, as for quicksort. A deterministic linear-time algorithm exists: divide the elements into groups of five, find the median of each group, recursively find the median of those medians, and use it as the pivot, which guarantees a split in which at least three tenths of the elements are discarded at each level. The resulting recurrence has a linear solution, though the constant is large enough that the randomized algorithm is preferred in practice.

Randomized Selection & Expected Linear Time

Finding the median does not require sorting. Randomized selection partitions like quicksort but then recurses into only the side containing the rank you want, throwing the other away. That single difference changes the recurrence from n log n to linear, because the work per level decreases geometrically instead of staying constant. The intuition is that a random pivot discards a constant fraction of the array with constant probability, so the expected total work is a geometric series summing to a constant times n.

{{illustration:algos-l08-f1}}

{{illustration:algos-l08-f2}}

Key relations

- Selection's recurrence. T(n) = T(3n/4) + Θ(n) = Θ(n) ; versus ; T(n) = 2T(n/2) + Θ(n) = Θ(nlog n)

Median of Medians, Deterministic Linear Time & Number Representation

A deterministic linear-time selection exists, and the trick is to choose the pivot carefully: split into groups of five, take each group's median, then recursively find the median of those medians. That guarantees the pivot discards at least three tenths of the array, which makes the recurrence linear with no randomness. The constant is large enough that randomized selection wins in practice, but the existence proof matters. Number representation underlies all of this: how integers and floats are encoded determines what operations cost and where precision is lost.

{{illustration:algos-l08-f3}}

{{illustration:algos-l08-f4}}

Key relations

- The median-of-medians recurrence and number encoding. T(n) = T(n/5) + T(7n/10) + O(n) = Θ(n) ; two′s complement: −x = x̄ + 1