Selection & Order Statistics
Finding the k-th smallest without sorting everything.
To find the median of a million numbers, you could sort them all, about twenty million comparisons, and read off the middle one. But sorting answers a million questions when you asked only one. Quickselect finds the median with about 3.4 million comparisons on average, and a cleverer pivot rule guarantees linear time even in the worst case.
What you’ll learn
- Define order statistics and compare four ways to select the k-th smallest: sorting, a size- heap, quickselect and median of medians, with their exact costs and whether each is worst case or expected.
- Implement quickselect from an explicit invariant, prove its expected linear time, and avoid its two traps: predictable pivots and repeated keys.
- Prove that the median minimizes the sum of absolute deviations, and apply medians and weighted medians to facility location.
- Recognize selection problems (k-th largest, top k, running medians, closest points) and their look-alikes, and use
std::nth_element,heapqand two-heap medians.
Selection, four ways
The k-th smallest of values is their k-th order statistic: the element that would sit at index after sorting (this lesson counts from 1 in words and indexes from 0 in code). The minimum is the first order statistic, the maximum the -th, and the median the middle one: the -th for odd , while even has two middle elements, the lower and the upper median.
Finding one order statistic is the selection problem. Sorting solves it, but sorting determines all order statistics at once, and one of them should be cheaper.
| Method | Time | Extra space | When to use it |
|---|---|---|---|
| Sort, then index | worst case | to | many different on the same data |
| Heap of the best so far | worst case | small ; streams that do not fit in memory | |
| Quickselect | expected, worst case | the practical default for one | |
| Median of medians | worst case | in place | guarantees against adversarial inputs |
A sensor emits readings one at a time, and you must report the 100 largest, with memory for only a few thousand numbers. Which method fits?
- Sort all the readings, then take the last 100
- Quickselect on all the readings
- A min-heap holding the 100 largest readings seen so far
- Median of medians
Show the answer
C. A min-heap holding the 100 largest readings seen so far
The heap's root is the weakest of the current top 100. Each new reading either loses to it, at the cost of one comparison, or replaces it in time. One pass, memory for 100 numbers, and time in the worst case.
Quickselect: partition, then go one way
Quickselect, Hoare's FIND algorithm (1961), borrows quicksort's partition step. Choose a pivot, move the smaller elements to its left and the larger ones to its right, and the pivot lands at its final sorted index . Quicksort would now recurse on both sides. To find index , only one side can hold it: stop if , continue left if , and right if .
import random
def quickselect(a, k):
"""The element of rank k (0-indexed) in list a. Reorders a."""
lo, hi = 0, len(a) - 1 # invariant: the answer is in a[lo..hi], lo <= k <= hi
while lo < hi:
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r] # a random pivot, moved to the end
pivot, store = a[hi], lo
for i in range(lo, hi): # Lomuto partition
if a[i] < pivot:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi] = a[hi], a[store] # the pivot lands at its final index
if k == store:
return a[k]
if k < store:
hi = store - 1 # keep only the side that holds k
else:
lo = store + 1
return a[k]quickselect([9, 4, 7, 1, 8, 2], 2) returns 4, the third smallest. Written as a loop, it needs extra space and cannot overflow the call stack.
Invariant. After partitioning around index , everything left of is smaller than and everything right of it is at least . So has rank , and the element of rank lies on the side that contains index ; discarding the other side never discards the answer.
Good pivots are common. Call a pivot good if its rank lies in the middle half of the current range. A uniformly random pivot is good with probability about , and after a good pivot at most of the range remains:
Phases. Let phase last while the range has between and elements. Each round of phase costs at most comparisons, and the phase ends at its first good pivot, after about 2 rounds in expectation. By linearity of expectation:
The truth is better still: Knuth's exact analysis gives comparisons for the minimum and about for the median, as the Optimal lesson Quickselect & Floyd–Rivest proves. If every pivot is bad, though, each round removes a single element:
A guaranteed pivot: median of medians
Random pivots give linear time on average. Blum, Floyd, Pratt, Rivest and Tarjan (1973) showed how to guarantee it: pick a pivot that is always roughly central. Split the elements into groups of 5, find the median of each group, and recursively find the median of those medians, . Then partition around and continue on one side, exactly as quickselect does.
Think first Why groups of 5, and not groups of 3?
Groups of 3 guarantee only about elements on each side of , so the recursion may keep of them, and only gives : the two fractions add up to exactly 1, so every level of the recursion tree still costs . Groups of 7 or more also work. The Optimal lesson Linear-Time Selection: Median of Medians proves all of this, and shows a trick that rescues groups of 3.
In libraries. C++ std::nth_element(first, first + k, last) rearranges a range so that position holds the element that would be there after sorting, with no larger element before it and no smaller one after it; the standard requires linear time on average. std::partial_sort sorts just the first positions. In Python, heapq.nsmallest(k, xs) and heapq.nlargest use a size- heap, , while statistics.median simply sorts its input.
#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>
int main() {
std::vector<int> a = {9, 4, 7, 1, 8, 2, 6};
std::size_t k = a.size() / 2; // rank 3 (0-indexed): the median
std::nth_element(a.begin(), a.begin() + k, a.end());
std::printf("median %d\n", a[k]); // 6
std::nth_element(a.begin(), a.begin() + 1, a.end(), std::greater<int>());
std::printf("2nd largest %d\n", a[1]); // 8
std::partial_sort(a.begin(), a.begin() + 3, a.end());
std::printf("3 smallest %d %d %d\n", a[0], a[1], a[2]); // 1 2 4
}C++17; the comments show the output. With std::greater, "the k-th position" counts from the largest.
What the median is good for
The median is a robust summary: send the largest value off to infinity and the median does not move, while the mean is dragged along. Better still, the median solves an optimization problem, and that is why selection shows up in problems that never mention it.
Between data points is linear. Moving right by a small (with no data point in between) brings it closer to every value above and farther from every value below it:
So falls while fewer than half of the values lie left of , and rises once more than half do. It is convex and piecewise linear, and its slope changes sign exactly at the median (it is zero between the two middle values when is even).
Example. For , the median 3 gives , while the mean 8.6 gives 42.8. With weights , the same slope argument shows that the weighted median, the first point where the cumulative weight reaches half of the total, minimizes :
This makes medians the answer to facility location on a line: to place a depot that minimizes the total travel distance to houses along a road, put it at a median house; if the deliveries have different sizes, at a weighted median. In the plane with Manhattan distance , the coordinates separate, so the best meeting point takes the median and the median : two selections, expected time.
Quantiles generalize the median: the -quantile is the element of rank , and a "99th percentile latency" is a selection problem. Over a stream too long to store, quantiles must be approximated, the subject of Top-k, Heavy Hitters & Streaming Quantiles.
Houses stand at positions 1, 4, 6, 15 and 30 along a road. Where the depot goes is up to you: what is the smallest possible total distance from the depot to all five houses?
Show the answer
40
Put the depot at the median house, position 6: . Moving it right by one step brings it closer to 2 houses but farther from 3, so the total rises; moving it left does the same in reverse. The mean, 11.2, would give 47.6.
Recognizing it
Selection hides behind several phrasings:
- "The k-th largest", "the median", "the 90th percentile" of data held in memory: one order statistic, so quickselect or
nth_element, expected. - "The k largest", "top k": select the k-th largest and keep everything above it, expected, then sort those if their order matters, . On a stream, keep a size- heap instead.
- A median that must be reported as the data arrive: two heaps.
- "Minimize the total absolute distance" to a single point: a median, possibly weighted.
| Problem, in brief | Key idea | Cost |
|---|---|---|
| The k-th largest element of an array | quickselect for index (0-indexed) | expected |
| The most frequent words in a text | count with a hash map, then select among the distinct words by count, or keep a size- heap | expected, or |
| The running median of a stream | a max-heap for the lower half and a min-heap for the upper half, sizes within one | per insertion, per query |
| The points closest to the origin | select by squared distance (no square roots needed) | expected |
| The meeting point with the least total Manhattan distance | the median and the median , separately | expected |
import heapq
class RunningMedian:
"""Median of a stream: a max-heap for the lower half, a min-heap for the upper half."""
def __init__(self):
self.low, self.high = [], [] # low holds negated values (heapq is a min-heap)
def add(self, x):
if self.low and x > -self.low[0]:
heapq.heappush(self.high, x)
else:
heapq.heappush(self.low, -x)
if len(self.low) > len(self.high) + 1: # rebalance: sizes differ by at most one
heapq.heappush(self.high, -heapq.heappop(self.low))
elif len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self): # the lower median
return -self.low[0]Invariant: every value in low is at most every value in high, and low holds the extra element when the count is odd, so its root is the lower median. Tested against sorting after every insertion.
Common bugs.
- Off by one in : decide whether counts from 0 or from 1, and remember that the k-th largest sits at index of the 0-indexed sorted order.
- Even : there are two medians; the problem says which one, or asks for their average.
- Repeated keys: a two-way partition can degrade to quadratic time on many copies of one value; partition three ways.
- Predictable pivots: first, last or middle elements have adversarial inputs; pick pivots at random.
- Mutation: quickselect and
nth_elementreorder their input; copy it first if the order matters. - Recursion depth: write quickselect as a loop, as above, so a run of bad pivots cannot overflow the call stack.
You must find the median of integers, each between 0 and 100. Which approach is simplest and safest?
- Sort with a comparison sort and take the middle element
- Quickselect with a two-way Lomuto partition
- Count how often each of the 101 values occurs, then walk the counts until half of the elements are passed
- A max-heap holding the smallest half of the elements
Show the answer
C. Count how often each of the 101 values occurs, then walk the counts until half of the elements are passed
With only 101 possible values, an array of 101 counters finds any order statistic in time, deterministically and without comparing elements to each other. That is counting sort's first phase, stopped halfway.
Key takeaways
- One order statistic costs less than sorting: quickselect takes expected time (about comparisons for the median), median of medians in the worst case, and a size- heap time with memory.
- Quickselect is quicksort that keeps only one side. Its invariant is that the answer stays in the current range; its traps are predictable pivots (quadratic on sorted input) and repeated keys (fixed by a three-way partition).
- Median of medians chooses a pivot with roughly elements on each side, so .
- The median minimizes the sum of absolute deviations, so it solves facility location on a line and, one coordinate at a time, under Manhattan distance; weighted medians handle weights.
- Signals: "k-th largest", "top k", "median", "percentile", "closest k" call for selection or heaps; a running median for two heaps; the k-th smallest of a huge implicit set for binary search on the answer.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In 0-indexed sorted order of distinct elements, which index holds the k-th largest, with counted from 1?
Show the answer
A.
The largest element sits at index , the second largest at , so the k-th largest sits at . Calling quickselect(a, n - k) finds it.
What is the worst-case running time of quickselect with uniformly random pivots, and why is it rarely seen?
- , the same as quicksort's average
- : random pivots remove the worst case entirely
- : a bad pivot in every round is possible, but such long runs of bad luck are extremely unlikely, and the expected time is
- , but only on sorted inputs
Show the answer
C. : a bad pivot in every round is possible, but such long runs of bad luck are extremely unlikely, and the expected time is
If every pivot happens to be an extreme element, each round removes one element and the total is . Randomness does not remove this case; it makes it improbable, with an expected cost of on every input. The worst case becomes a matter of luck instead of a property of the input.
Why does the median-of-medians pivot guarantee linear time?
- The pivot is always the exact median
- At least about elements lie on each side of the pivot, so each round keeps at most about , and
- Groups of 5 can be sorted in constant time, so the whole algorithm makes comparisons
- It never needs to recurse
Show the answer
B. At least about elements lie on each side of the pivot, so each round keeps at most about , and
The pivot is only approximately central, but reliably so. The recursion on the medians handles elements and the main recursion at most about ; since these fractions sum to less than 1, the costs per level form a decreasing geometric series, in total.
Houses stand at 2, 3, 10 and 50 along a road. Where should a depot go to minimize the total distance to the four houses?
- At 16.25, the mean of the positions
- Only at 6.5, halfway between the two middle houses
- At 50, beside the most isolated house
- Anywhere from 3 to 10: every such point gives the same, smallest total
Show the answer
D. Anywhere from 3 to 10: every such point gives the same, smallest total
With an even number of houses, the slope of the total distance is zero between the two middle positions: moving right brings the depot 1 closer to two houses and 1 farther from the other two. Every point in gives ; the mean, 16.25, gives 67.5.
A running median keeps a max-heap for the lower half and a min-heap for the upper half, letting the lower half hold one extra element. After inserting 5, 1, 9 and 3, in that order, what are the two roots?
- 1 and 9
- 3 and 5
- 5 and 9
- 3 and 9
Show the answer
B. 3 and 5
The four values split into a lower half and an upper half , so the roots are 3 (the largest of the lower half) and 5 (the smallest of the upper half): the two medians. Each insertion cost , and the median is read from the roots in .
Go deeper
- Linear-Time Selection: Median of Medians · The deterministic O(n) algorithm of Blum, Floyd, Pratt, Rivest and Tarjan.
- Quickselect & Floyd–Rivest · Expected comparisons, sampling, and selection in n + min(k, n − k) + o(n).
- Top-k, Heavy Hitters & Streaming Quantiles · Heaps for the k largest, Misra–Gries and quantile sketches.
Further reading
- C. A. R. Hoare, "Algorithm 65: Find," Communications of the ACM 4(7) (1961), 321–322.
- M. Blum, R. W. Floyd, V. Pratt, R. L. Rivest & R. E. Tarjan, "Time bounds for selection," Journal of Computer and System Sciences 7(4) (1973), 448–461.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 9.