Sub topic 3
Quickselect: Recursing Into Only One Side
This chapter assumes you can read Python functions, list comprehensions, and recursion, that you are comfortable with zero-based indexing, and that you know what O(n) and O(n log n) mean. Earlier chapters defined the k-th smallest element and showed how to partition a list around a pivot. Here we combine those two ideas into quickselect.
The Core Idea
Quicksort partitions a list around a pivot and then sorts both sides. Quickselect starts with the same partition step. After partitioning, though, it already knows how many elements are smaller than the pivot, so it can tell which side holds the k-th smallest element. It recurses into that side only and drops the other side.
After one partition around a pivot p, the elements fall into three groups:
lows: every element strictly less thanppivots: every element equal tophighs: every element strictly greater thanp
Suppose the whole list were sorted. All of lows would come first, then all of pivots, then all of highs. Their sorted positions are:
| Group | Sorted index range (zero-based) |
|---|---|
| `lows` | `0` to `len(lows) - 1` |
| `pivots` | `len(lows)` to `len(lows) + len(pivots) - 1` |
| `highs` | `len(lows) + len(pivots)` to `n - 1` |
Comparing k against these ranges tells you which group contains the answer. You don't need to know the order inside any group.
The Simple Implementation
The version below builds new lists rather than partitioning in place. It is short, so the logic is easy to see. The next chapter turns it into an in-place loop.
import random
def quickselect_simple(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_simple(lows, k)
if k < len(lows) + len(pivots):
return pivot
return quickselect_simple(highs, k - len(lows) - len(pivots))
print(quickselect_simple([9, 1, 8, 2, 7, 3], 2)) # 3Each line has a job:
random.choice(items)picks the pivot. A later chapter compares pivot strategies. Random choice is used here because no fixed input can force it to make bad choices every time.- The three comprehensions do the partition. Each one scans the list once, so the step costs O(n) time and O(n) extra memory.
- The first
ifhandles the case where the answer is smaller than the pivot. The answer keeps its rank insidelows, because everything removed was larger than it. - The second
ifhandles the case whereklands among the copies of the pivot. Every element in that range equalspivot, so the function returns it right away. - The last line handles the case where the answer is larger than the pivot. You discard
len(lows) + len(pivots)elements that are all smaller than the answer, so its rank insidehighsdrops by that amount.
Why the Rank Adjustment Is Correct
The function depends on one invariant:
Removing elements that are all larger than the answer leaves its rank unchanged, since its rank counts only smaller elements. That is why recursing into lows keeps k. Removing m elements that are all smaller than the answer lowers its rank by exactly m. That is why recursing into highs uses k - m, where m = len(lows) + len(pivots).
The recursion always ends. The pivots group contains at least one element, the pivot itself, and that group is never passed to a recursive call. So every recursive call gets a strictly shorter list. A list of length 1 has lows and highs empty, k must be 0, and the second if returns.
Tracing an Example
Random pivots make traces hard to reproduce. The version below takes the pivot-choosing function as a parameter, so we can plug in a deterministic rule (take the middle element) and print each step.
def quickselect_traced(items, k, choose, depth=0):
pivot = choose(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]
print(f"{' ' * depth}items={items} k={k} pivot={pivot} "
f"lows={lows} pivots={pivots} highs={highs}")
if k < len(lows):
return quickselect_traced(lows, k, choose, depth + 1)
if k < len(lows) + len(pivots):
return pivot
return quickselect_traced(highs, k - len(lows) - len(pivots), choose, depth + 1)
middle = lambda xs: xs[len(xs) // 2]
print(quickselect_traced([9, 1, 8, 2, 7, 3], 2, middle))Output:
items=[9, 1, 8, 2, 7, 3] k=2 pivot=2 lows=[1] pivots=[2] highs=[9, 8, 7, 3]
items=[9, 8, 7, 3] k=0 pivot=7 lows=[3] pivots=[7] highs=[9, 8]
items=[3] k=0 pivot=3 lows=[] pivots=[3] highs=[]
3Walk through it:
- Call 1. The pivot
2splits off one smaller element and one equal element.k = 2is not below 1 and not below 2, so the answer is inhighs. Two elements are discarded, so the new rank is2 - 1 - 1 = 0. - Call 2. We now want the smallest element of
[9, 8, 7, 3]. The pivot7leaves one smaller element,k = 0 < 1, so we recurse intolowswithkunchanged. - Call 3. The list is
[3], and the function returns3.
Sorting [9, 1, 8, 2, 7, 3] gives [1, 2, 3, 7, 8, 9], and index 2 is 3, which matches. The function never sorted anything, and it never looked at 9 or 8 again after the second call.
Quicksort Versus Quickselect: The Shape of the Work
Quicksort's call tree branches at every node. Quickselect follows a single path down that same tree.
In quicksort, each level of the tree touches all n elements in total, and there are about log n levels, for O(n log n). In quickselect, each level touches one sublist that is roughly half the size of the one above it. If every pivot split the list evenly, the total work would be:
n + n/2 + n/4 + n/8 + ... < 2n
That sum is the intuition behind quickselect's expected O(n) time. Real random pivots don't split exactly in half, and an unlucky run of pivots can shrink the list by only one element per call, which costs O(n²). A later chapter proves the expected bound and covers the worst case properly. For now, the point is that dropping one side is what replaces n log n with something linear.
Common Mistakes
These bugs show up often in quickselect code. Each one either returns a wrong answer or never stops.
Putting equal elements into `lows` or `highs`
Using <= in the lows comprehension looks harmless:
lows = [x for x in items if x <= pivot] # buggyThe pivot now lands in lows. If every element equals the pivot (for example [5, 5, 5]), then lows is the whole list. The recursive call gets an input of the same size, and the function recurses until Python raises RecursionError. A separate pivots group guarantees progress.
Forgetting to subtract `len(pivots)`
Writing k - len(lows) when recursing into highs treats the pivot copies as if they were still in the list. The adjusted rank is then too large by len(pivots). Sometimes this causes an IndexError deep in the recursion. Other times it silently returns the wrong element.
Off-by-one between zero-based and one-based k
The code here uses zero-based k, so k = 0 means the minimum. If your caller thinks of "the 3rd smallest" as k = 3, convert once at the boundary:
def kth_smallest_one_based(items, k):
return quickselect_simple(items, k - 1)Convert only at the boundary. Mixing the two conventions inside the recursion produces bugs that are hard to trace.
No validation of k
quickselect_simple assumes a non-empty list and 0 <= k < len(items). If items is empty, random.choice raises IndexError. If k is too large, the function recurses into an empty highs, and the same error appears from a confusing place. Check the input once at the public entry point:
import random
def quickselect_checked(items, k):
"""Validate inputs, then delegate to the recursive helper."""
if not items:
raise ValueError("cannot select from an empty list")
if not 0 <= k < len(items):
raise IndexError(f"k={k} out of range for list of length {len(items)}")
return _select(list(items), k)
def _select(items, k):
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 _select(lows, k)
if k < len(lows) + len(pivots):
return pivot
return _select(highs, k - len(lows) - len(pivots))
print(quickselect_checked([4, 2, 6], 0)) # 2Validating once is enough. The invariant guarantees that k stays in range in every recursive call.
Testing Against a Reference
Bugs from randomness and off-by-one errors show up quickly when you compare against sorting on many random inputs. Include inputs with many duplicates, because duplicates are where the pivots group matters.
import random
def quickselect_simple(items, k):
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_simple(lows, k)
if k < len(lows) + len(pivots):
return pivot
return quickselect_simple(highs, k - len(lows) - len(pivots))
for trial in range(2000):
n = random.randint(1, 30)
data = [random.randint(0, 5) for _ in range(n)] # small range forces duplicates
k = random.randrange(n)
expected = sorted(data)[k]
got = quickselect_simple(data, k)
assert got == expected, (data, k, got, expected)
print("all tests passed")Limits of This Version
The list-building version is useful for understanding the algorithm, but it has practical costs:
| Concern | Behavior of `quickselect_simple` |
|---|---|
| Extra memory | Allocates new lists at each level; O(n) expected total, plus Python object overhead |
| Passes per level | Three comprehensions scan the list three times |
| Recursion depth | Expected O(log n), but O(n) in the worst case, which can exceed Python's default limit of about 1000 frames |
| Input mutation | None; the caller's list is untouched |
The recursive call is the last thing each branch does, so it is a tail call. Python does not optimize tail calls, but a tail-recursive function converts directly into a loop. The next chapter does that conversion and also replaces the list comprehensions with in-place Lomuto partitioning, which removes the extra memory and the depth limit.
Exercise
Run quickselect_traced on [4, 4, 1, 4, 9] with k = 3 and the middle-element pivot rule. List the pivot, the three groups, and the k value at each call, and give the final result.
Show answer
Call 1: items [4, 4, 1, 4, 9], pivot is items[2] = 1. lows = [], pivots = [1], highs = [4, 4, 4, 9]. k = 3 is not < 0 and not < 1, so recurse into highs with k = 3 - 0 - 1 = 2. Call 2: items [4, 4, 4, 9], pivot is items[2] = 4. lows = [], pivots = [4, 4, 4], highs = [9]. k = 2 is not < 0 but is < 3, so return 4. Check: sorted is [1, 4, 4, 4, 9] and index 3 is 4.
Exercise
A colleague's version builds lows with x <= pivot, builds highs with x > pivot, and drops the pivots group (returning the pivot when k == len(lows) - 1). Give an input where this never terminates and explain why.
Show answer
Any list in which every element equals the pivot, for example [7, 7, 7] with k = 0. Every element satisfies x <= 7, so lows is the whole list and has the same length as the input. Because k = 0 < len(lows) = 3, the function recurses on an identical list forever (until RecursionError). The original version avoids this because the pivots group always removes at least one element from consideration.
Exercise
Assume every pivot happens to split the current list exactly in half. About how many element comparisons does quickselect_simple make in total on a list of n elements, counting each of the three comprehensions separately? How does this compare with sorting?
Show answer
Each level scans its list three times, so a level of size m costs about 3m comparisons. The sizes are n, n/2, n/4, ..., which sum to less than 2n, so the total is under 6n comparisons, which is O(n). Comparison sorting needs about n log2 n comparisons, and for large n that grows faster than any constant times n. For n = 1,000,000 that is roughly 20,000,000 comparisons versus under 6,000,000.