Sub topic 16
Quickselect: Finding the k-th Smallest Element
This chapter assumes you already know the Lomuto partition scheme and randomized pivot selection from earlier chapters. It also assumes you are comfortable with 0-based indexing and expected-case Big-O reasoning.
Sometimes you need one order statistic instead of a fully sorted array. An order statistic is the value that would sit at a given index if the array were sorted. Common examples are the median, the 90th percentile, and the 10th smallest score. Sorting first costs O(n log n). Quickselect gets the answer in expected O(n) by reusing quicksort's partition step.
The Key Observation
After partitioning, the pivot is at its final sorted index p. Every element to its left is smaller and every element to its right is at least as large. So when you want index k, three cases are possible:
- If
k == p, the pivot is the answer. - If
k < p, the answer is in the left part. - If
k > p, the answer is in the right part.
Quicksort recurses into both sides. Quickselect continues into only the side that holds k and ignores the other one. Because only one side is ever processed, the recursion becomes a simple loop.
Implementation
The code below includes the partition helpers so it runs as shown.
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)) # 4Sorted, the input is [1, 2, 4, 7, 9], so index 2 holds 4.
Why It Is Linear on Average
A random pivot splits the range reasonably well most of the time. If each step roughly halves the range, the total work is about n + n/2 + n/4 + ..., which is at most 2n. A more careful analysis that allows for uneven random splits still gives an expected bound of a small constant times n, so the expected cost is O(n). The log n factor from quicksort disappears because quickselect never goes back to process the other side.
The worst case is still O(n²). It happens when every pivot is the smallest or largest element in the range. Randomization makes this very unlikely on any input. If you need a guaranteed O(n) bound, the median-of-medians pivot rule provides one, but its larger constant factor usually makes it slower in practice.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Treating `k` as 1-based | Off-by-one result | Pass `k - 1` for the "k-th smallest" in 1-based terms |
| Expecting the input to be unchanged | Caller's list is reordered | Pass a copy: `quickselect(list(xs), k)` |
| `k` outside `0..n-1` | Index error, or the loop never finishes | Validate `k` before calling |
| Fixed last-element pivot on sorted data | Quadratic slowdown | Use `randomized_partition` |
After quickselect returns, the array is partly ordered. Everything before index k is no larger than a[k], and everything after it is no smaller. C++'s std::nth_element relies on the same guarantee.
Exercise
Use quickselect to write a function median(xs) for an odd-length list that does not modify the caller's list. What is its expected running time?
Show answer
def median(xs): return quickselect(list(xs), len(xs) // 2). Copying takes O(n) and quickselect takes expected O(n), so the total is expected O(n).
Exercise
Why does quickselect have expected O(n) time while quicksort has expected O(n log n), even though both use the same partition step?
Show answer
Quicksort recurses into both sides, so every level of recursion does about n work across roughly log n levels. Quickselect continues into only one side, so the range sizes form a shrinking series that sums to a constant times n.