Randomized Quickselect
Sorting finds every order statistic at once, at a cost of . 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 for every rank and every input, and about 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 -th smallest (), look for the value that would sit at index of the sorted array. Partition; the pivot lands at its sorted index . If , done. If , 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 .
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 + 1Invariant. At the start of each iteration, , and the value that belongs at sorted index of the original array is in , at sorted index of the current array.
Partitioning only moves values within and puts the pivot at its final sorted index, so the values left of are exactly the ones whose sorted index is less than . Keeping the side that contains 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.
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 -th largest is the same as finding the -th smallest: that is the practice problem K-th Largest.
In C++
The randomized version with a fixed-seed std::mt19937:
#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, , and fix the target rank . As in quicksort, every comparison is between a pivot and another element of the current subarray, and no pair is compared twice. When are and () compared?
Consider the set of ranks from to : it contains , and the target . 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 or , the two are compared;
- if it is anything else in the set, it separates from , 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
Summing this over all pairs gives the exact expectation. Its closed form, due to Knuth, is
and splitting the sum into the pairs on each side of and the pairs that straddle it shows that it is less than for every . It is largest for the median, where it is about ; for the minimum or maximum it is about .
Why the sum is at most 4n
Group the pairs into three cases and bound each.
- Both at or above the target, . The probability is . For each there are choices of , and , so this part is less than .
- Both at or below the target, . Symmetrically, for each there are choices of , each with probability : less than in total.
- Straddling the target, . The probability is . For a given distance (from 2 to ) at most pairs straddle , contributing at most , so this part is less than .
Altogether .
The program computes the expectation three ways for small : 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 .
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.
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 that the formula gives for , 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 . The bound is on the expectation, not on each run. The worst case is still , 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 and the target index is , where does quickselect continue?
- In
- In , still looking for index
- In , looking for index
- In both parts
What is the expected number of comparisons of randomized quickselect for the median of values, to leading order?
- about
When searching for rank , the values and () are compared with probability...
Why does quickselect run in expected linear time while quicksort needs ?
- It uses a better pivot
- It recurses into only one side of each partition, so the subproblem sizes shrink geometrically on average
- It makes no comparisons
- It sorts only half the array