Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

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-kk 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, heapq and two-heap medians.

Selection, four ways

The k-th smallest of nn values is their k-th order statistic: the element that would sit at index k−1k - 1 after sorting (this lesson counts kk from 1 in words and indexes from 0 in code). The minimum is the first order statistic, the maximum the nn-th, and the median the middle one: the n+12\tfrac{n+1}{2}-th for odd nn, while even nn 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 nn order statistics at once, and one of them should be cheaper.

MethodTimeExtra spaceWhen to use it
Sort, then indexΘ(nlog⁡n)\Theta(n \log n) worst caseO(1)O(1) to O(n)O(n)many different kk on the same data
Heap of the best kk so farO(nlog⁡k)O(n \log k) worst caseO(k)O(k)small kk; streams that do not fit in memory
QuickselectΘ(n)\Theta(n) expected, Θ(n2)\Theta(n^2) worst caseO(1)O(1)the practical default for one kk
Median of mediansΘ(n)\Theta(n) worst caseO(log⁡n)O(\log n) in placeguarantees against adversarial inputs
Every comparison-based method must inspect every element, so Ω(n)\Omega(n) is a lower bound; for the minimum alone, exactly n−1n - 1 comparisons are necessary and sufficient, since every other element must lose at least once.
Check your understanding

A sensor emits 10910^9 readings one at a time, and you must report the 100 largest, with memory for only a few thousand numbers. Which method fits?

  1. Sort all the readings, then take the last 100
  2. Quickselect on all the readings
  3. A min-heap holding the 100 largest readings seen so far
  4. 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 O(log⁡100)O(\log 100) time. One pass, memory for 100 numbers, and O(nlog⁡k)O(n \log k) 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 pp. Quicksort would now recurse on both sides. To find index kk, only one side can hold it: stop if p=kp = k, continue left if k<pk < p, and right if k>pk > p.

python
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 O(1)O(1) extra space and cannot overflow the call stack.

DerivationCorrectness and expected linear time
  1. a[lo..p−1]  <  a[p]  ≤  a[p+1..hi]a[lo..p-1] \;<\; a[p] \;\le\; a[p+1..hi]

    Invariant. After partitioning a[lo..hi]a[lo..hi] around index pp, everything left of pp is smaller than a[p]a[p] and everything right of it is at least a[p]a[p]. So a[p]a[p] has rank pp, and the element of rank kk lies on the side that contains index kk; discarding the other side never discards the answer.

  2. Pr⁡[good]≈12,good  ⇒  new size≤34⋅size\Pr[\text{good}] \approx \tfrac12, \qquad \text{good} \;\Rightarrow\; \text{new size} \le \tfrac34 \cdot \text{size}

    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 1/21/2, and after a good pivot at most 3/43/4 of the range remains:

  3. E[comparisons]  ≲  ∑j≥02(34)jn  =  8n\E[\text{comparisons}] \;\lesssim\; \sum_{j \ge 0} 2 \left(\tfrac34\right)^j n \;=\; 8n

    Phases. Let phase jj last while the range has between (3/4)j+1n(3/4)^{j+1} n and (3/4)jn(3/4)^j n elements. Each round of phase jj costs at most (3/4)jn(3/4)^j n comparisons, and the phase ends at its first good pivot, after about 2 rounds in expectation. By linearity of expectation:

  4. E[Cmedian]≈3.39 n,Cworst=n(n−1)2=Θ(n2)\E[C_{\text{median}}] \approx 3.39\,n, \qquad C_{\text{worst}} = \tfrac{n(n-1)}{2} = \Theta(n^2)

    The truth is better still: Knuth's exact analysis gives 2(n−Hn)≈2n2(n - H_n) \approx 2n comparisons for the minimum and about 2(1+ln⁡2) n≈3.39 n2(1 + \ln 2)\,n \approx 3.39\,n 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, xx. Then partition around xx and continue on one side, exactly as quickselect does.

T(n)  ≤  T ⁣(⌈n/5⌉)+T ⁣(7n10+6)+O(n)⟹T(n)=O(n)T(n) \;\le\; T\!\left(\lceil n/5 \rceil\right) + T\!\left(\tfrac{7n}{10} + 6\right) + O(n) \quad\Longrightarrow\quad T(n) = O(n)
At least half of the group medians are ≥x\ge x, and each of their groups holds at least 3 elements ≥x\ge x, so roughly 3n/103n/10 elements lie on each side of xx and the recursion keeps at most about 7n/107n/10. Because 15+710<1\tfrac15 + \tfrac{7}{10} < 1, the work shrinks geometrically from level to level.
Think first Why groups of 5, and not groups of 3?

Groups of 3 guarantee only about n/3n/3 elements on each side of xx, so the recursion may keep 2n/32n/3 of them, and T(n)≤T(n/3)+T(2n/3)+O(n)T(n) \le T(n/3) + T(2n/3) + O(n) only gives Θ(nlog⁡n)\Theta(n \log n): the two fractions add up to exactly 1, so every level of the recursion tree still costs Θ(n)\Theta(n). 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 kk 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 kk positions. In Python, heapq.nsmallest(k, xs) and heapq.nlargest use a size-kk heap, O(nlog⁡k)O(n \log k), while statistics.median simply sorts its input.

cpp
#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.

DerivationProof by slopes
  1. S(c+δ)−S(c)=δ⋅(#{i:xi<c}−#{i:xi>c})S(c + \delta) - S(c) = \delta \cdot \big(\#\{i : x_i < c\} - \#\{i : x_i > c\}\big)

    Between data points SS is linear. Moving cc right by a small δ>0\delta > 0 (with no data point in between) brings it closer to every value above cc and farther from every value below it:

  2. slope<0  left of the median,slope>0  right of it\text{slope} < 0 \ \text{ left of the median}, \qquad \text{slope} > 0 \ \text{ right of it}

    So SS falls while fewer than half of the values lie left of cc, 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 nn is even).

  3. ∑xi≤mwi  ≥  12∑iwiat the first such point m\sum_{x_i \le m} w_i \;\ge\; \tfrac12 \sum_i w_i \quad \text{at the first such point } m

    Example. For 1,2,3,7,301, 2, 3, 7, 30, the median 3 gives S=2+1+0+4+27=34S = 2 + 1 + 0 + 4 + 27 = 34, while the mean 8.6 gives 42.8. With weights wiw_i, the same slope argument shows that the weighted median, the first point where the cumulative weight reaches half of the total, minimizes ∑iwi∣xi−c∣\sum_i w_i \abs{x_i - c}:

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 ∣Δx∣+∣Δy∣\abs{\Delta x} + \abs{\Delta y}, the coordinates separate, so the best meeting point takes the median xx and the median yy: two selections, O(n)O(n) expected time.

Quantiles generalize the median: the pp-quantile is the element of rank ⌈pn⌉\lceil pn \rceil, 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.

Predict before you look

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: 5+2+0+9+24=405 + 2 + 0 + 9 + 24 = 40. 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, O(n)O(n) expected.
  • "The k largest", "top k": select the k-th largest and keep everything above it, O(n)O(n) expected, then sort those kk if their order matters, O(klog⁡k)O(k \log k). On a stream, keep a size-kk 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 briefKey ideaCost
The k-th largest element of an arrayquickselect for index n−kn - k (0-indexed)O(n)O(n) expected
The kk most frequent words in a textcount with a hash map, then select among the dd distinct words by count, or keep a size-kk heapO(n)O(n) expected, or O(n+dlog⁡k)O(n + d \log k)
The running median of a streama max-heap for the lower half and a min-heap for the upper half, sizes within oneO(log⁡n)O(\log n) per insertion, O(1)O(1) per query
The kk points closest to the originselect by squared distance (no square roots needed)O(n)O(n) expected
The meeting point with the least total Manhattan distancethe median xx and the median yy, separatelyO(n)O(n) expected
The first, fourth and fifth rows are one selection each; the third keeps selection alive under insertions.
python
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 kk: decide whether kk counts from 0 or from 1, and remember that the k-th largest sits at index n−kn - k of the 0-indexed sorted order.
  • Even nn: 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_element reorder 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.
Check your understanding

You must find the median of 10610^6 integers, each between 0 and 100. Which approach is simplest and safest?

  1. Sort with a comparison sort and take the middle element
  2. Quickselect with a two-way Lomuto partition
  3. Count how often each of the 101 values occurs, then walk the counts until half of the elements are passed
  4. 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 O(n+101)O(n + 101) 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 Θ(n)\Theta(n) expected time (about 3.39n3.39n comparisons for the median), median of medians Θ(n)\Theta(n) in the worst case, and a size-kk heap O(nlog⁡k)O(n \log k) time with O(k)O(k) 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 3n/103n/10 elements on each side, so T(n)≤T(n/5)+T(7n/10)+O(n)=O(n)T(n) \le T(n/5) + T(7n/10) + O(n) = O(n).
  • 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.

Question 1

In 0-indexed sorted order of nn distinct elements, which index holds the k-th largest, with kk counted from 1?

  1. n−kn - k
  2. k−1k - 1
  3. n−k−1n - k - 1
  4. n−k+1n - k + 1
Show the answer

A. n−kn - k

The largest element sits at index n−1n - 1, the second largest at n−2n - 2, so the k-th largest sits at n−kn - k. Calling quickselect(a, n - k) finds it.

Question 2

What is the worst-case running time of quickselect with uniformly random pivots, and why is it rarely seen?

  1. Θ(nlog⁡n)\Theta(n \log n), the same as quicksort's average
  2. Θ(n)\Theta(n): random pivots remove the worst case entirely
  3. Θ(n2)\Theta(n^2): a bad pivot in every round is possible, but such long runs of bad luck are extremely unlikely, and the expected time is Θ(n)\Theta(n)
  4. Θ(n2)\Theta(n^2), but only on sorted inputs
Show the answer

C. Θ(n2)\Theta(n^2): a bad pivot in every round is possible, but such long runs of bad luck are extremely unlikely, and the expected time is Θ(n)\Theta(n)

If every pivot happens to be an extreme element, each round removes one element and the total is Θ(n2)\Theta(n^2). Randomness does not remove this case; it makes it improbable, with an expected cost of Θ(n)\Theta(n) on every input. The worst case becomes a matter of luck instead of a property of the input.

Question 3

Why does the median-of-medians pivot guarantee linear time?

  1. The pivot is always the exact median
  2. At least about 3n/103n/10 elements lie on each side of the pivot, so each round keeps at most about 7n/107n/10, and 15+710<1\tfrac15 + \tfrac{7}{10} < 1
  3. Groups of 5 can be sorted in constant time, so the whole algorithm makes n/5n/5 comparisons
  4. It never needs to recurse
Show the answer

B. At least about 3n/103n/10 elements lie on each side of the pivot, so each round keeps at most about 7n/107n/10, and 15+710<1\tfrac15 + \tfrac{7}{10} < 1

The pivot is only approximately central, but reliably so. The recursion on the medians handles n/5n/5 elements and the main recursion at most about 7n/107n/10; since these fractions sum to less than 1, the costs per level form a decreasing geometric series, O(n)O(n) in total.

Question 4

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?

  1. At 16.25, the mean of the positions
  2. Only at 6.5, halfway between the two middle houses
  3. At 50, beside the most isolated house
  4. 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 [3,10][3, 10] gives 5555; the mean, 16.25, gives 67.5.

Question 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. 1 and 9
  2. 3 and 5
  3. 5 and 9
  4. 3 and 9
Show the answer

B. 3 and 5

The four values split into a lower half {1,3}\{1, 3\} and an upper half {5,9}\{5, 9\}, 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 O(log⁡n)O(\log n), and the median is read from the roots in O(1)O(1).

Go deeper

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.