Sub topic 16
Quickselect: Finding the k-th Smallest Element
This chapter assumes you have read the earlier chapters on the Lomuto partition scheme, randomized quicksort, and three-way partitioning. You should also be comfortable with Big-O notation and with summing a geometric series.
Sometimes you need one order statistic instead of a sorted array. The median, the 90th percentile, or the 10th smallest latency are examples. The k-th order statistic is the value that would sit at index k if the array were sorted. Sorting gives you the answer in O(n log n), but most of that work goes into ordering elements you never look at. Quickselect reuses quicksort's partition step and skips that wasted work. Its expected running time is O(n).
The Core Idea: Recurse on One Side Only
After a partition, the pivot sits at its final sorted index p. Every element to the left is smaller than or equal to it, and every element to the right is larger than or equal to it. That gives three cases for a target index k:
- If
k == p, the pivot is the answer. - If
k < p, the answer lies in the left part, and the right part can be ignored. - If
k > p, the answer lies in the right part, and the left part can be ignored.
Quicksort recurses into both sides. Quickselect continues into only one. Because only one branch survives, the recursion becomes a loop and needs no call stack at all.
A Complete Implementation
The listing below includes the Lomuto and randomized partition functions from earlier chapters, so it runs on its own.
import random
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
def randomized_partition(a, lo, hi):
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
return lomuto_partition(a, lo, hi)
def quickselect(a, k):
lo, hi = 0, len(a) - 1
while True:
if lo == hi:
return a[lo]
p = randomized_partition(a, lo, hi)
if k == p:
return a[k]
elif k < p:
hi = p - 1
else:
lo = p + 1
print(quickselect([7, 2, 9, 4, 1], 2)) # 4The loop maintains one invariant: index k always lies inside [lo, hi], and every element outside that range is already on the correct side of position k. The range shrinks by at least one element per iteration because the pivot is excluded, so the loop terminates.
Tracing an Example
To make the trace repeatable, suppose the random pivot happens to be the last element every time, so the pivot is a[hi]. We search for k = 2 in [7, 2, 9, 4, 1].
| Step | lo..hi | Pivot | Array after partition | p | Decision |
|---|---|---|---|---|---|
| 1 | 0..4 | 1 | [1, 2, 9, 4, 7] | 0 | k > p, so lo = 1 |
| 2 | 1..4 | 7 | [1, 2, 4, 7, 9] | 3 | k < p, so hi = 2 |
| 3 | 1..2 | 4 | [1, 2, 4, 7, 9] | 2 | k == p, return 4 |
The array still is not guaranteed to be sorted when quickselect returns. Only position k is guaranteed: everything before it is at most a[k], and everything after it is at least a[k]. Libraries expose this guarantee directly, for example numpy.partition and C++ std::nth_element.
Why the Expected Time Is Linear
Each partition of a range of size m costs Θ(m). The question is how quickly the range shrinks.
Call a pivot "good" if it lands in the middle half of the current range, between the 25th and 75th percentile. A uniformly random pivot is good with probability 1/2. After a good pivot, the surviving side has at most 3m/4 elements, whichever side k is on. A bad pivot never makes the range larger.
Group the iterations into phases, where a phase ends after the first good pivot. The number of partitions in a phase follows a geometric distribution with success probability 1/2, so its expected value is 2. During phase j the range has at most (3/4)^j · n elements. The expected total work is therefore at most:
2 · (n + (3/4)n + (3/4)²n + ...) = 2 · n · 1 / (1 − 3/4) = 8n
The bound is loose. A sharper analysis gives about 3.4n comparisons for the median. The conclusion stays the same: expected O(n), compared with quicksort's O(n log n). The difference comes from the recursion tree. Quicksort's tree has about log n levels, and each level does O(n) total work. Quickselect follows a single path, and the sizes along that path shrink geometrically.
Edge Cases and Gotchas
The input is modified
Quickselect rearranges the list in place. If the caller needs the original order, copy the list first: quickselect(list(data), k).
Out-of-range k
The loop above never checks k. With k >= len(a) or a negative k, it narrows to some range that does not contain k and returns a wrong value. With an empty list, a[lo] raises an IndexError. Validate k at the entry point.
Many duplicate keys
Lomuto sends every element equal to the pivot to the right side. If all elements are equal, each partition puts the pivot at lo, the range shrinks by one, and the cost becomes quadratic even with a random pivot. Three-way partitioning fixes this. Every element equal to the pivot is settled in one pass, and if k falls inside the equal block, the search stops immediately.
import random
def quickselect3(a, k):
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
while lo < hi:
pivot = a[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
# Now a[lo:lt] < pivot, a[lt:gt+1] == pivot, a[gt+1:hi+1] > pivot
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
return a[lo]
def kth_smallest(data, k):
return quickselect3(list(data), k)
values = [5, 1, 5, 5, 3, 5, 9, 5]
print([kth_smallest(values, k) for k in range(len(values))])
# [1, 3, 5, 5, 5, 5, 5, 9]
print(kth_smallest([2] * 100000, 50000)) # 2, in one partition passFinding the median
For an odd length n, the median is at index n // 2. For an even length, the median is often defined as the mean of indices n // 2 - 1 and n // 2. You can run two selections. Alternatively, after selecting index n // 2, take the maximum of the left part, since all of those elements are at most a[n // 2].
Guaranteed Linear Time and Production Variants
If an adversary can influence your input or your random source, expected time may not be good enough. The median-of-medians algorithm (Blum, Floyd, Pratt, Rivest, and Tarjan, 1973) picks a pivot that is guaranteed to fall between roughly the 30th and 70th percentile, which gives O(n) worst-case time. Its constant factor is large, so it is usually slower in practice than randomized quickselect.
Production libraries handle this the same way introsort does. Introselect, used by many std::nth_element implementations and by numpy.partition, runs ordinary quickselect and switches to a fallback with a guaranteed bound if the ranges stop shrinking fast enough. Like introsort, these implementations also hand small ranges to insertion sort.
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Sort, then index | O(n log n) | Depends on sort | Simplest. Worth it if you need many order statistics |
| `heapq.nsmallest(k + 1, data)` | O(n log k) | O(k) | Good for small k or streaming data. Does not modify the input |
| Randomized quickselect | Expected O(n), worst O(n²) | O(1) | Fast in practice. Modifies the input |
| Median of medians | O(n) worst case | O(log n) with recursion | Large constant. Mostly used as a fallback |
| Introselect | O(n) worst case | O(1) | What C++ and NumPy implementations use |
Exercise
Why does quickselect run in expected O(n) while quicksort with the same random pivots runs in expected O(n log n)? Answer in terms of the work done per partition and how many ranges are partitioned.
Show answer
Both algorithms spend linear time partitioning each range. Quicksort partitions both sides of every pivot, so each of its roughly log n recursion levels covers all n elements, which totals O(n log n). Quickselect keeps only the side that contains k, so it partitions one range per step. The range sizes shrink geometrically in expectation (at most 3/4 after each good pivot), and their sum is bounded by a constant times n.
Exercise
Run the Lomuto-based quickselect on a list of 10,000 copies of the same value with k = 5000. About how many element comparisons does it make, and what change fixes the problem?
Show answer
Every element equals the pivot, so a[j] < pivot is never true and the pivot always lands at index lo. Each step removes one element, so the loop runs about 5000 times on ranges of size 10,000, 9,999, and so on down to about 5,000, which is roughly 37 million comparisons, or Θ(n²). Three-way partitioning (quickselect3) puts all equal elements into the middle block in a single pass, and since k falls inside that block, it returns after one partition of about 10,000 comparisons.
Exercise
A caller writes median = quickselect(scores, len(scores) // 2) and later prints scores, expecting the original order. What goes wrong, and how should the code be written?
Show answer
Quickselect rearranges the list in place, so scores comes back partially reordered around the median. The caller should pass a copy, quickselect(list(scores), len(scores) // 2), or use a wrapper such as kth_smallest that copies the list internally.