TExcelTAD
Home › Sorting & Order Statistics › Randomized Quickselect

Randomized Quickselect

Sorting finds every order statistic at once, at a cost of Θ(nlg⁡n)\Theta(n \lg n). If you want just one, say the median, most of that work is wasted. Quickselect borrows quicksort's partition step but recurses into only one side: the side that contains the rank you are looking for. With a random pivot, the expected number of comparisons is at most 4n4n for every rank and every input, and about 3.39n3.39n for the median. Selection is linear.

The algorithm is due to Hoare, like quicksort; it is also called FIND or randomized select. It builds on Lomuto Partitioning and its analysis reuses the pair-counting argument of Randomized Quicksort and Its Expected Cost.

The algorithm

To find the kk-th smallest (1≤k≤n1 \le k \le n), look for the value that would sit at index t=k−1t = k - 1 of the sorted array. Partition; the pivot lands at its sorted index pp. If p=tp = t, done. If t<pt < p, the answer is among the smaller values on the left; otherwise among the larger values on the right. In both cases its index stays the same, because partitioning keeps everything on the correct side of pp.

text
QUICKSELECT(a, k)                 // returns the k-th smallest value, 1 <= k <= n
1  lo = 0,  hi = n - 1,  t = k - 1
2  loop
3      if lo == hi:  return a[lo]
4      swap a[hi] with a uniformly random element of a[lo..hi]
5      p = LOMUTO-PARTITION(a, lo, hi)
6      if p == t:       return a[p]
7      else if t < p:   hi = p - 1
8      else:            lo = p + 1

Invariant. At the start of each iteration, lo≤t≤hilo \le t \le hi, and the value that belongs at sorted index tt of the original array is in a[lo..hi]a[lo..hi], at sorted index tt of the current array.

Partitioning only moves values within a[lo..hi]a[lo..hi] and puts the pivot at its final sorted index, so the values left of pp are exactly the ones whose sorted index is less than pp. Keeping the side that contains tt therefore keeps the answer, and the subarray shrinks by at least one (the pivot) every time, so the loop terminates.

The animation runs the deterministic version (last element as pivot, no line 4) on 9 values to find the 7th smallest. It uses <= in the partition, so values equal to the pivot go left; with distinct values that changes nothing.

python · try it yourself
def quickselect(a, k, trace=False):
    a = list(a)
    lo, hi, t = 0, len(a) - 1, k - 1
    while True:
        if lo == hi:
            if trace: print(f"only index {lo} is left: the answer is {a[lo]}")
            return a[lo]
        pivot, i = a[hi], lo
        for j in range(lo, hi):              # Lomuto with <=, as in the animation
            if a[j] <= pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        p = i
        if trace: print(f"partition {lo}..{hi} around {pivot}: it lands at {p}   {a}")
        if p == t:
            return a[p]
        if t < p:
            hi = p - 1
        else:
            lo = p + 1

print("7th smallest:", quickselect([7, 2, 9, 4, 1, 8, 3, 6, 5], 7, trace=True))
partition 0..8 around 5: it lands at 4   [2, 4, 1, 3, 5, 8, 7, 6, 9]
partition 5..8 around 9: it lands at 8   [2, 4, 1, 3, 5, 8, 7, 6, 9]
partition 5..7 around 6: it lands at 5   [2, 4, 1, 3, 5, 6, 7, 8, 9]
partition 6..7 around 8: it lands at 7   [2, 4, 1, 3, 5, 6, 7, 8, 9]
only index 6 is left: the answer is 7
7th smallest: 7

Four partitions on shrinking ranges, as in the animation, and not a single comparison spent on the left part after the first partition. Finding the kk-th largest is the same as finding the (n−k+1)(n - k + 1)-th smallest: that is the practice problem K-th Largest.

In C++

The randomized version with a fixed-seed std::mt19937:

cpp · try it yourself
#include <cstdio>
#include <random>
#include <utility>
#include <vector>

std::mt19937 rng(7);

int quickselect(std::vector<int> a, int k, long long& comparisons) {
    int lo = 0, hi = static_cast<int>(a.size()) - 1, t = k - 1;
    for (;;) {
        if (lo == hi) return a[lo];
        int r = lo + static_cast<int>(rng() % static_cast<unsigned>(hi - lo + 1));
        std::swap(a[r], a[hi]);
        int pivot = a[hi], i = lo;
        for (int j = lo; j < hi; ++j) {
            ++comparisons;
            if (a[j] < pivot) std::swap(a[i++], a[j]);
        }
        std::swap(a[i], a[hi]);
        if (i == t) return a[i];
        if (t < i) hi = i - 1; else lo = i + 1;
    }
}

int main() {
    std::vector<int> a = {7, 2, 9, 4, 1, 8, 3, 6, 5};
    long long c = 0;
    for (int k = 1; k <= 9; ++k) std::printf(k > 1 ? " %d" : "%d", quickselect(a, k, c));
    std::printf("\n");
    const int n = 100001;
    std::vector<int> big(n);
    for (int i = 0; i < n; ++i) big[i] = (i * 7919) % n;    // a permutation of 0..n-1
    c = 0;
    int median = quickselect(big, (n + 1) / 2, c);
    std::printf("median of 0..%d: %d, %lld comparisons = %.2f n\n", n - 1, median, c, static_cast<double>(c) / n);
}
1 2 3 4 5 6 7 8 9
median of 0..100000: 50000, 311774 comparisons = 3.12 n

Expected comparisons: counting pairs again

Rename the values by rank, z1<⋯<znz_1 < \cdots < z_n, and fix the target rank kk. As in quicksort, every comparison is between a pivot and another element of the current subarray, and no pair is compared twice. When are ziz_i and zjz_j (i<ji < j) compared?

Consider the set of ranks from min⁡(i,k)\min(i, k) to max⁡(j,k)\max(j, k): it contains ziz_i, zjz_j and the target zkz_k. Until a pivot is chosen from this set, every pivot is either below all of it or above all of it, so the whole set stays in the current subarray (the target is always kept, and the set's other members are on the target's side). At the moment the first pivot is chosen from the set:

  • if it is ziz_i or zjz_j, the two are compared;
  • if it is anything else in the set, it separates ziz_i from zjz_j, or it is the target and the search stops, or it lies between the pair and the target and throws the pair away. In each case they are never compared.

The pivot is uniform over the subarray, so each member of the set is equally likely to be first, and

Pr⁡[zi and zj compared]=2max⁡(j,k)−min⁡(i,k)+1.\Pr[z_i \text{ and } z_j \text{ compared}] = \frac{2}{\max(j, k) - \min(i, k) + 1}.

Summing this over all pairs gives the exact expectation. Its closed form, due to Knuth, is

E[C(n,k)]=2((n+1)Hn−(n+3−k)Hn+1−k−(k+2)Hk+n+3),\mathbb{E}[C(n, k)] = 2\bigl((n+1)H_n - (n+3-k)H_{n+1-k} - (k+2)H_k + n + 3\bigr),

and splitting the sum into the pairs on each side of kk and the pairs that straddle it shows that it is less than 4n4n for every kk. It is largest for the median, where it is about 2(1+ln⁡2) n≈3.386 n2(1 + \ln 2)\,n \approx 3.386\,n; for the minimum or maximum it is about 2n2n.

Why the sum is at most 4n

Group the pairs into three cases and bound each.

  • Both at or above the target, k≤i<jk \le i < j. The probability is 2j−k+1\frac{2}{j - k + 1}. For each j>kj > k there are j−kj - k choices of ii, and 2(j−k)j−k+1<2\frac{2(j - k)}{j - k + 1} < 2, so this part is less than 2(n−k)2(n - k).
  • Both at or below the target, i<j≤ki < j \le k. Symmetrically, for each i<ki < k there are k−ik - i choices of jj, each with probability 2k−i+1\frac{2}{k - i + 1}: less than 2(k−1)2(k - 1) in total.
  • Straddling the target, i<k<ji < k < j. The probability is 2j−i+1\frac{2}{j - i + 1}. For a given distance d=j−id = j - i (from 2 to n−1n - 1) at most d−1d - 1 pairs straddle kk, contributing at most 2(d−1)d+1<2\frac{2(d - 1)}{d + 1} < 2, so this part is less than 2(n−2)2(n - 2).

Altogether E[C(n,k)]<2(n−k)+2(k−1)+2(n−2)=4n−6\mathbb{E}[C(n, k)] < 2(n - k) + 2(k - 1) + 2(n - 2) = 4n - 6.

The program computes the expectation three ways for small nn: by the recurrence of the algorithm (every pivot rank equally likely), by the pair sum, and by the closed form. Then it evaluates the closed form for large nn.

python · try it yourself
from fractions import Fraction
from functools import lru_cache
import math

def H(m):
    return sum(Fraction(1, i) for i in range(1, m + 1))

@lru_cache(maxsize=None)
def by_recurrence(n, k):
    """expected comparisons: n - 1 for the partition, then recurse into one side"""
    if n <= 1:
        return Fraction(0)
    total = Fraction(0)
    for p in range(1, n + 1):          # pivot rank, each with probability 1/n
        if p < k: total += by_recurrence(n - p, k - p)
        elif p > k: total += by_recurrence(p - 1, k)
    return n - 1 + total / n

def by_pairs(n, k):
    return sum(Fraction(2, max(j, k) - min(i, k) + 1) for i in range(1, n + 1) for j in range(i + 1, n + 1))

def closed_form(n, k):
    return 2 * ((n + 1) * H(n) - (n + 3 - k) * H(n + 1 - k) - (k + 2) * H(k) + n + 3)

print("all three agree for n <= 12, every k:",
      all(by_recurrence(n, k) == by_pairs(n, k) == closed_form(n, k) for n in range(1, 13) for k in range(1, n + 1)))
print("n = 5:", [str(closed_form(5, k)) for k in range(1, 6)])

def closed_float(n, k):
    h = lambda m: math.log(m) + 0.5772156649 + 1 / (2 * m) if m > 0 else 0.0
    return 2 * ((n + 1) * h(n) - (n + 3 - k) * h(n + 1 - k) - (k + 2) * h(k) + n + 3)

n = 10 ** 6
for name, k in [("minimum", 1), ("10th percentile", n // 10), ("median", n // 2)]:
    print(f"n = 10^6, {name:>15}: {closed_float(n, k) / n:.3f} n comparisons expected")
print(f"2(1 + ln 2) = {2 * (1 + math.log(2)):.3f}")
all three agree for n <= 12, every k: True
n = 5: ['163/30', '32/5', '101/15', '32/5', '163/30']
n = 10^6,         minimum: 2.000 n comparisons expected
n = 10^6, 10th percentile: 2.650 n comparisons expected
n = 10^6,          median: 3.386 n comparisons expected
2(1 + ln 2) = 3.386

Simulation

The bound holds for every input, so the program runs randomized quickselect for the median on sorted input (the worst case of the deterministic version) and on random input.

python · try it yourself
import random

def quickselect_count(a, k, rng):
    a = list(a)
    lo, hi, t, c = 0, len(a) - 1, k - 1, 0
    while lo < hi:
        r = rng.randint(lo, hi)
        a[r], a[hi] = a[hi], a[r]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            c += 1
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]; i += 1
        a[i], a[hi] = a[hi], a[i]
        if i == t: break
        if t < i: hi = i - 1
        else: lo = i + 1
    return a[t], c

rng = random.Random(31)
n, runs = 5001, 30
for name, data in [("sorted", list(range(n))), ("random", rng.sample(range(n), n))]:
    counts = []
    for _ in range(runs):
        value, c = quickselect_count(data, (n + 1) // 2, rng)
        assert value == n // 2
        counts.append(c)
    print(f"{name}: median found, mean {sum(counts) / runs / n:.2f} n comparisons, max {max(counts) / n:.2f} n")
sorted: median found, mean 3.23 n comparisons, max 5.28 n
random: median found, mean 3.02 n comparisons, max 5.78 n

Both means are a little below the 3.37n3.37n that the formula gives for n=5001n = 5001, which is within the sampling noise of 30 runs: the cost of quickselect varies a lot from run to run, and single runs can even exceed 4n4n. The bound is on the expectation, not on each run. The worst case is still Θ(n2)\Theta(n^2), if every pivot happens to be the largest or smallest remaining value. The next lesson removes even that possibility: Median of Medians picks a pivot that is guaranteed to be good, at the price of a larger constant.

Test yourself

After a partition puts the pivot at index pp and the target index is t>pt > p, where does quickselect continue?

  1. In a[lo..p−1]a[lo..p-1]
  2. In a[p+1..hi]a[p+1..hi], still looking for index tt
  3. In a[p+1..hi]a[p+1..hi], looking for index t−pt - p
  4. In both parts

What is the expected number of comparisons of randomized quickselect for the median of nn values, to leading order?

  1. nn
  2. about 3.39n3.39n
  3. 2nln⁡n2n \ln n
  4. nlg⁡nn \lg n

When searching for rank kk, the values ziz_i and zjz_j (i<j<ki < j < k) are compared with probability...

  1. 2j−i+1\frac{2}{j - i + 1}
  2. 2k−i+1\frac{2}{k - i + 1}
  3. 1n\frac{1}{n}
  4. 2n\frac{2}{n}

Why does quickselect run in expected linear time while quicksort needs Θ(nlg⁡n)\Theta(n \lg n)?

  1. It uses a better pivot
  2. It recurses into only one side of each partition, so the subproblem sizes shrink geometrically on average
  3. It makes no comparisons
  4. It sorts only half the array