Algorithms · Visualized
Order Statistics
Order Statistics
Find the k-th smallest, medians, and top-k without full sorting.
Big-O: Quickselect O(n) average; heaps O(n log k).
Order Statistics
Find the k-th smallest without fully sorting — selection in linear expected time.
Order-statistics problems ask for the k-th smallest element (medians are k = n/2) or the top-k set. Quickselect partitions exactly like quicksort but recurses into only one side, giving expected O(n) time (each round processes a geometrically shrinking share) with a quadratic worst case on adversarial pivots. BFPRT (median-of-medians) chooses pivots guaranteed to discard ≥ 30% of the remainder, making worst-case O(n) — at the cost of constants that make quickselect preferable in practice. For streams and top-k queries, heaps of size k answer in O(n log k).
The general recipe
- Choose a pivot (random for quickselect, median-of-medians for worst-case guarantees).
- Partition the array around the pivot — its final index tells you its rank r.
- If r == k, done; recurse into only the side containing rank k (the other side is finished forever).
- For top-k variants, either quickselect a boundary or keep a min/max-heap of size k while scanning.
- Handle duplicates by partitioning into three bands (<, =, >) so equal keys cannot stall the recursion.
Vocabulary you'll meet everywhere here
- k-th order statistic
- the element that would be at index k if the array were sorted
- Quickselect
- quicksort’s single-branch recursion — expected O(n), worst O(n²)
- Median of medians (BFPRT)
- pivot selection guaranteeing linear worst case
- Three-way partition
- Dutch-flag grouping into less/equal/greater to survive duplicate keys
- Heap of size k
- maintain the k best candidates in O(log k) per element
Where this family shows up
- Medians and percentiles without sorting, leaderboard top-k
- K closest points to origin, k most frequent elements
- Running median over streams via two heaps
Common pitfalls
- Recursing into both halves — that is quicksort; selection recurses into exactly one
- Adversarial pivot patterns (sorted input with first-element pivots) degrade quickselect — randomize
- k is 0-indexed in code but often 1-indexed in problem statements — verify before comparing ranks
- Ignoring duplicate keys with two-way partitioning can loop without progress
import random
def quickselect(arr, k):
# kth smallest, 0-indexed
lo, hi = 0, len(arr) - 1
while lo <= hi:
pivot = random.choice(arr[lo:hi + 1])
less, equal, greater = [], [], []
for v in arr[lo:hi + 1]:
if v < pivot: less.append(v)
elif v == pivot: equal.append(v)
else: greater.append(v)
if k < len(less):
arr = less; hi = len(arr) - 1; lo = 0
elif k < len(less) + len(equal):
return pivot
else:
k -= len(less) + len(equal)
arr = greater; hi = len(arr) - 1; lo = 0Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.