Order Statistics and Median
Overview
The -th order statistic of a set of elements is the -th smallest element. The minimum is the 1st order statistic (); the maximum is the -th; the median (lower median) is the -th.
The selection problem: given a set of distinct numbers and an integer where , find the element larger than exactly others.
Finding Minimum and Maximum
A simple linear scan finds the minimum (or maximum) in comparisons:
min = A[1]
for j = 2 to n:
if A[j] < min: min = A[j]
Finding both minimum and maximum simultaneously can be done in comparisons: process elements in pairs, compare within each pair, then compare the larger against the running maximum and the smaller against the running minimum.
| Task | Comparisons |
|---|---|
| Find min only | |
| Find max only | |
| Find min and max naively | |
| Find min and max optimally |
Quickselect
Quickselect uses the same partition subroutine as quicksort, but only recurses on the side containing the desired order statistic:
- Call
PARTITION(A, p, r)which rearrangesA[p..r]around a pivot and returns pivot index . - Let (the rank of the pivot within the subarray).
- If , return
A[q]— the pivot is the answer. - If , recurse on
A[p..q-1]for the -th statistic. - If , recurse on
A[q+1..r]for the -th statistic.
Complexity
- Expected: . Each partition is on a subarray of size , but the subarray shrinks by a constant factor in expectation.
- Worst case: , when the pivot is always the minimum or maximum (e.g. already-sorted or reverse-sorted input).
Improvements
- Randomised pivot: Choose the pivot at random; makes worst-case inputs unlikely.
- Median-of-three: Pick three elements, use their median as pivot. Guarantees at least one element on each side, reducing the worst-case probability from to .
- Three-way partition: Split into pivot, pivot, pivot. Excellent when many duplicates exist.
Median-of-Medians (Blum-Floyd-Pratt-Rivest-Tarjan)
This deterministic algorithm finds the -th order statistic in worst-case time:
- Divide the elements into groups of 5. Find the median of each group (constant-time per group via insertion sort on 5 elements).
- Recursively find the median of these medians; use it as the pivot.
- Partition around this median-of-medians pivot.
- Recurse on the appropriate side.
Why : At least elements are guaranteed to be greater than the pivot, and symmetrically for less than. So even the larger side is at most elements. The recurrence:
For , the constant factor works out; for smaller , any constant-time method suffices.
Practical Considerations
For most applications, simply sorting the array in and reading the -th element is fast enough and far simpler to implement. Quickselect (randomised) is used in practice when is large and sorting overhead is undesirable.
Summary
| Method | Time (expected) | Time (worst case) |
|---|---|---|
| Sort then pick -th | ||
| Quickselect (randomised) | ||
| Median-of-medians | ||
| Find min or max | ||
| Find min and max |