Sub topic 8
Quickselect Versus Sorting and Heaps
This chapter assumes you already know how quickselect partitions and recurses into one side, that its expected running time is O(n), and that its worst case is O(n^2). You should also be comfortable with Big-O notation and Python's heapq module. The goal here is practical: when should you use quickselect, and when is sorting or a heap the better tool?
Three Ways to Get the k-th Smallest Element
There are three common ways to find the k-th smallest element (0-based) of a list of n items:
- Sort, then index. Call
sorted(items)[k]. This costs O(n log n) time and O(n) extra space for the copy. - Use a heap of size k+1.
heapq.nsmallest(k + 1, items)[-1]keeps a bounded max-heap of the k+1 smallest items seen so far. This costs O(n log k) time and O(k) extra space. - Quickselect. Partition and recurse into one side. This costs expected O(n) time and O(1) extra space when done in place.
All three return the same value. They differ in cost, in what else they give you, and in what they require from the input.
import heapq
import random
import timeit
def quickselect(items, k):
"""Return the k-th smallest element (0-based) of a non-empty list."""
pivot = random.choice(items)
lows = [x for x in items if x < pivot]
pivots = [x for x in items if x == pivot]
highs = [x for x in items if x > pivot]
if k < len(lows):
return quickselect(lows, k)
if k < len(lows) + len(pivots):
return pivot
return quickselect(highs, k - len(lows) - len(pivots))
def by_sorting(items, k):
return sorted(items)[k]
def by_heap(items, k):
return heapq.nsmallest(k + 1, items)[-1]
data = [random.randint(0, 10**9) for _ in range(200_000)]
for k in (10, len(data) // 2):
answers = {f(data, k) for f in (by_sorting, by_heap, quickselect)}
assert len(answers) == 1
for f in (by_sorting, by_heap, quickselect):
t = timeit.timeit(lambda: f(data, k), number=3) / 3
print(f"k={k:>6} {f.__name__:<11} {t * 1000:7.1f} ms")The output depends on your machine, but you will usually see two things. With small k, the heap is very fast, because log k is tiny and heapq is written in C. With k near the median, the heap is the slowest of the three, and quickselect beats sorting. Python's built-in sorted is also C code, so a pure-Python quickselect wins by less than the Big-O analysis suggests. On a few thousand items, sorting is often faster.
What Each Approach Gives You Beyond One Element
Speed is only part of the choice. Each method leaves behind a different amount of useful structure.
| Approach | Time | Extra space | Also gives you | Needs all data at once? |
|---|---|---|---|---|
| Sort then index | O(n log n) | O(n), or O(1) if in place | Every order statistic in O(1) afterwards | Yes |
| Heap of size k+1 | O(n log k) | O(k) | The k+1 smallest, in sorted order | No, works on a stream |
| Quickselect | Expected O(n), worst O(n^2) | O(1) in place | The k smallest before index k, unordered | Yes |
Some consequences of this table:
- Many queries on the same data. If you need the 10th, 50th, and 90th percentiles of one array, sort once. After that, each query is a single index lookup. Running quickselect three times costs about 3n work, and repeated quickselect calls stop paying off quickly.
- Top-k results in order. Quickselect puts the k smallest elements before position k, but in no particular order. If you need them ranked, you still have to sort those k items, for a total of O(n + k log k). This is often still the cheapest option. A heap gives you sorted output directly.
- Streaming or huge input. A heap processes one item at a time and keeps only k+1 of them in memory. Quickselect needs random access to the whole array, so it cannot run on a generator or a file that does not fit in memory.
A Decision Guide
In real code, the "quickselect" branch should usually mean a library function rather than one you write yourself. Library versions guard against the O(n^2) worst case and run as compiled code. A later chapter covers std::nth_element and numpy.partition.
Exercises
Exercise
You must report the 25th, 50th, and 75th percentiles of a 10-million-element in-memory array. Which approach do you pick, and why?
Show answer
Sort once, in O(n log n), then read all three positions by index. Three separate quickselects would cost about 3n expected work, without a worst-case guarantee. You could also run a library routine such as numpy.partition with all three indices at once. A heap is a poor fit, because k is about n/2 for the median.
Exercise
A log processor reads an unbounded stream of response times and must keep the 100 slowest seen so far. Why is quickselect unsuitable, and what should you use?
Show answer
Quickselect needs random access to the whole data set at once, and a stream is never complete. Keep a min-heap of size 100. For each new value larger than the heap's minimum, call heapreplace. Each item costs O(log 100), and the memory used stays fixed.
Exercise
What is the total cost of returning the k smallest elements in sorted order using quickselect, and how does it compare with sorting everything?
Show answer
Quickselect to position k costs expected O(n), and sorting the first k elements costs O(k log k), for O(n + k log k) in total. When k is much smaller than n, this beats O(n log n) for a full sort.