Sub topic 8
Quickselect Versus Sorting and Heaps
Quickselect is one way to find the k-th smallest element. Sorting the whole array and using a heap are two others. Each one fits different situations. This chapter compares their cost, memory use, effect on the input, and behavior on streams. It ends with a set of rules for picking one.
This chapter assumes you know Big-O notation, Python lists, and the heapq module at a basic level. It also assumes you have read the earlier chapters on quickselect and its expected O(n) analysis. As in the rest of the tutorial, k is zero-based: k = 0 means the minimum.
The Three Families of Solutions
Every practical method for the selection problem belongs to one of three families.
- Sort, then index. Sort all n elements and read position k. This does more work than needed, because it orders elements you never look at.
- Heap-based selection. Keep a heap, either a small one holding the best k + 1 candidates or a heap built over the whole input. You then pop or inspect the top.
- Partition-based selection. Quickselect and its relatives split the data around a pivot and throw away the side that cannot hold the answer.
The three approaches order different amounts of the data. Sorting produces a full order. A bounded heap orders only the candidates, and only loosely. Quickselect guarantees just one fact at the end: everything left of position k is no larger than a[k], and everything right of it is no smaller.
Sorting: The Baseline
Sorting is the simplest correct answer:
def kth_by_sort(items, k):
"""Return the k-th smallest element (0-based) by sorting a copy."""
return sorted(items)[k]
print(kth_by_sort([9, 1, 8, 2, 7, 3], 2)) # 3The cost is O(n log n) time. sorted makes a new list, so it also needs O(n) extra memory. list.sort() sorts in place, but Python's Timsort can still allocate a merge buffer of up to n/2 elements.
Sorting looks wasteful next to quickselect's expected O(n), but it has real advantages:
- Repeated queries are cheap. After one sort, every later question ("what is the 10th smallest? the 90th percentile? the median?") costs O(1). If you need m different order statistics from the same data and m is more than a handful, one sort usually beats m quickselect runs.
- The order is complete. If you also need the k smallest elements in order, sorting gives them to you for free.
- It is stable and predictable. Sorting has no bad pivot luck and no O(n²) worst case. Timsort also runs in close to O(n) on input that is already nearly sorted.
- In Python, it runs in C. This point matters more than the asymptotics for moderate n, as the benchmark below shows.
Heaps: Two Different Strategies
A heap is a tree-shaped structure, stored in an array, that gives O(1) access to its smallest element (a min-heap) or largest element (a max-heap). Insertion and removal cost O(log size). Python's heapq provides a min-heap on top of a plain list.
You can use a heap for selection in two very different ways.
Strategy A: A Bounded Max-Heap of Size k + 1
Keep the k + 1 smallest elements seen so far in a max-heap. The root is the largest of those candidates. When a new element is smaller than the root, it replaces the root. After the whole input has been seen, the root is the k-th smallest element.
heapq only provides a min-heap, so the code stores negated values to simulate a max-heap:
import heapq
import itertools
def kth_smallest_stream(stream, k):
"""Return the k-th smallest (0-based) value from any iterable of numbers.
Uses O(k) memory and O(n log k) time. Works on generators and files.
"""
it = iter(stream)
heap = [-x for x in itertools.islice(it, k + 1)]
if len(heap) < k + 1:
raise IndexError("k out of range")
heapq.heapify(heap) # max-heap via negation
for x in it:
if x < -heap[0]: # smaller than the largest candidate
heapq.heapreplace(heap, -x)
return -heap[0]
print(kth_smallest_stream([9, 1, 8, 2, 7, 3], 2)) # 3
print(kth_smallest_stream((x * 7 % 101 for x in range(1000)), 0)) # 0The cost is O(n log k) time and O(k) memory. Two properties make this strategy stand out:
- It works on streams. It reads each element once, in order, and never needs random access. You can feed it lines from a file of any size, a network socket, or a generator. Quickselect needs the whole array in memory, and it needs the ability to swap elements.
- It is cheap when k is small. For k = 10 and n = 10 million, log k is about 3.5. The heap stays tiny and usually fits in the CPU's fastest cache. Most elements fail the
x < -heap[0]test after one comparison and never touch the heap.
When k is close to n, the advantage disappears: log k approaches log n, and the heap uses O(n) memory. The trick is to flip the problem. The k-th smallest element is the (n − 1 − k)-th largest, so you can keep a min-heap of the n − k largest values instead. Pick whichever heap is smaller.
Strategy B: Heapify Everything, Then Pop k Times
import heapq
def kth_by_heapify(items, k):
"""Return the k-th smallest (0-based) by building a full min-heap."""
if not 0 <= k < len(items):
raise IndexError("k out of range")
heap = list(items)
heapq.heapify(heap) # O(n)
for _ in range(k):
heapq.heappop(heap) # O(log n) each
return heap[0]
print(kth_by_heapify([9, 1, 8, 2, 7, 3], 2)) # 3heapify runs in O(n), so the total cost is O(n + k log n). For small k this is linear, and it never hits a quadratic worst case. The popped elements come out in sorted order, so you get the k smallest values already sorted. The cost is O(n) memory for the copy, or a destroyed input if you heapify in place.
Quickselect in This Comparison
From the earlier chapters, randomized quickselect runs in expected O(n) time and O(1) extra memory when done in place. Its worst case is O(n²). It has these practical traits:
- It mutates the input. The in-place version reorders the array. If the caller needs the original order, you pay O(n) to copy it first.
- It leaves a useful partial order. After
quickselect(a, k), the slicea[:k]holds the k smallest elements in no particular order. Sorting that slice gives a sorted top-k in O(n + k log k) total, which is the best possible bound for that task. - It needs random access and the whole input. It cannot run on a stream.
- Repeated queries are not free. Each call costs O(n) again. Partitions left by earlier calls help a little, but sorting once is simpler when you have many queries.
The Full Comparison
| Method | Time | Extra memory | Mutates input | Works on a stream | Sorted top-k as a by-product |
|---|---|---|---|---|---|
| `sorted(items)[k]` | O(n log n) | O(n) | No | No | Yes |
| `list.sort()` then index | O(n log n) | up to O(n) | Yes | No | Yes |
| Bounded heap of size k + 1 | O(n log k) | O(k) | No | Yes | After O(k log k) extra sort |
| Heapify + k pops | O(n + k log n) | O(n) for a copy | No (with copy) | No | Yes, in pop order |
| Quickselect, in place | Expected O(n), worst O(n²) | O(1) iterative | Yes | No | After O(k log k) sort of `a[:k]` |
| Quickselect on a copy | Expected O(n), worst O(n²) | O(n) | No | No | After O(k log k) sort of the copy's prefix |
Asymptotics Versus Reality in Python
Big-O hides constant factors. In CPython the constant factors heavily favor code that runs in C. sorted, heapq.heapify, heapq.heapreplace, and heapq.nsmallest are all implemented in C. A pure-Python quickselect runs every comparison and swap through the interpreter.
The benchmark below checks that all methods agree, then times them. Run it yourself, because the numbers depend on your machine and Python version.
import heapq
import itertools
import random
import timeit
def kth_by_sort(items, k):
return sorted(items)[k]
def kth_by_heapify(items, k):
heap = list(items)
heapq.heapify(heap)
for _ in range(k):
heapq.heappop(heap)
return heap[0]
def kth_by_bounded_heap(items, k):
it = iter(items)
heap = [-x for x in itertools.islice(it, k + 1)]
heapq.heapify(heap)
for x in it:
if x < -heap[0]:
heapq.heapreplace(heap, -x)
return -heap[0]
def kth_by_nsmallest(items, k):
return heapq.nsmallest(k + 1, items)[-1]
def kth_by_quickselect(items, k):
a = list(items) # copy so callers keep their order
lo, hi = 0, len(a) - 1
while lo < hi:
p = random.randint(lo, hi)
a[p], a[hi] = a[hi], a[p]
pivot, store = a[hi], lo
for i in range(lo, hi):
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store]
if k == store:
return a[k]
if k < store:
hi = store - 1
else:
lo = store + 1
return a[k]
methods = [kth_by_sort, kth_by_heapify, kth_by_bounded_heap,
kth_by_nsmallest, kth_by_quickselect]
random.seed(1)
n = 200_000
data = [random.random() for _ in range(n)]
for k in (10, n // 2):
expected = kth_by_sort(data, k)
for f in methods:
assert f(data, k) == expected, f.__name__
print(f"k = {k}")
for f in methods:
t = timeit.timeit(lambda: f(data, k), number=3) / 3
print(f" {f.__name__:22s} {t * 1000:8.1f} ms")Typical results show the following patterns. Your exact numbers will differ.
- For small k, the bounded heap and
nsmallestwin by a wide margin. Most elements are rejected after one C-level comparison. - For k = n/2,
sortedis often competitive with the pure-Python quickselect, or faster. The interpreter's overhead per operation outweighs the log n factor at this size. kth_by_heapifywith k = n/2 is the slowest option, because it performs n/2 pops at O(log n) each.
Gotchas That Change the Decision
The caller's array gets reordered. In-place quickselect leaves the list scrambled in a partial order. If other code relies on the original order, this causes a silent bug. Either copy first or document the mutation, as std::nth_element does.
Adversarial input. A fixed-pivot quickselect hit by crafted input, for example in a web service that computes medians of user-submitted data, can be pushed into O(n²). Random pivots make this unlikely but not impossible. When you need guaranteed bounds, use sorting, heaps, or the guaranteed-linear methods covered later in this tutorial.
Duplicates. A two-way Lomuto quickselect degrades on arrays with many equal keys. Sorting and heaps are unaffected. If your data has few distinct values, use three-way partitioning, or check whether a counting approach fits better.
Non-numeric keys and key= functions. sorted and heapq.nsmallest accept key=. A homemade quickselect has to add that parameter itself. Decorating items as (key, index, item) tuples works but adds memory and comparison cost.
NaN values. float('nan') compares false against everything. The result is a wrong answer, with no exception raised, from sorting, heaps, and quickselect alike. Filter NaNs out before selecting.
Choosing a Method
These rules apply in this order:
- The data is a stream or too large for memory: use a bounded heap. It is the only option here that reads the input once.
- You need many order statistics, or the k smallest in sorted order, and k is large: sort once.
- k is small compared to n (or n − k is): use a bounded heap or
heapq.nsmallest. It is fast, uses little memory, and does not touch the input. - You need one order statistic from a large in-memory array, and k is in the middle: use quickselect, preferably through a library routine.
- You need hard worst-case bounds: sort, or use a deterministic selection method.
Exercises
Exercise
You must report the 100 smallest response times from a 50 GB log file, one number per line, on a machine with 8 GB of RAM. Which method fits, and what are its time and memory costs?
Show answer
Use a bounded max-heap of size 100. Read the file line by line and replace the heap's root whenever a value is smaller than it. Time is O(n log 100), which is effectively O(n). Memory is O(100), so it is independent of file size. Sorting and quickselect both need the data in memory, and the file does not fit. At the end, sort the 100 heap entries if you need them in order.
Exercise
A dashboard computes the 50th, 90th, 95th, and 99th percentiles of the same list of one million latencies on every refresh. A colleague suggests running quickselect four times. What do you recommend, and why?
Show answer
Sort once, in O(n log n), and read all four positions in O(1) each. Four quickselect runs cost about 4n expected work plus four O(n) copies if the input must be preserved, and in Python each run goes through the interpreter, while sorting runs once in C. If percentile queries keep growing in number, sorting wins even more clearly.
Exercise
Why does kthbyheapify become slow when k = n/2, even though heapify is O(n)? What change makes a heap approach reasonable for k near n?
Show answer
After the O(n) heapify, it performs k = n/2 pops at O(log n) each, so the total is O(n log n), with worse constants than sorting. For k near n, flip the problem: the k-th smallest is the (n − 1 − k)-th largest, so keep a bounded min-heap of the n − k largest values, which is small when k is close to n.
Exercise
After an in-place quickselect(a, k), what do you know about a[:k], and how can you get the k smallest elements in sorted order? What is the total cost?
Show answer
a[:k] contains exactly the k smallest elements, with equal values counted correctly, but in arbitrary order. Each of them is no larger than a[k]. Sort the slice with sorted(a[:k]) to get them in order. The total cost is expected O(n) for the selection plus O(k log k) for the sort.