Sub topic 3
Quickselect: Recursing Into Only One Side
This chapter assumes you can read Python functions and list comprehensions and follow a recursive call. It also assumes you know the selection problem and partitioning from the two previous chapters. Here we combine them into quickselect. The key idea is that after a partition, you only need to search one of the groups.
The Core Observation
Partitioning splits a list around a pivot into three groups:
lows: elements smaller than the pivotpivots: elements equal to the pivothighs: elements larger than the pivot
Once you know the size of each group, you know which group holds the k-th smallest element (0-based). Every element of lows comes before every element of pivots in sorted order, and every element of pivots comes before every element of highs. So the position k lands in exactly one of three ranges:
| Condition | Where the answer is | What to do next |
|---|---|---|
| `k < len(lows)` | In `lows` | Recurse into `lows` with the same `k` |
| `len(lows) <= k < len(lows) + len(pivots)` | In `pivots` | Return the pivot |
| `k >= len(lows) + len(pivots)` | In `highs` | Recurse into `highs` with `k - len(lows) - len(pivots)` |
Quicksort recurses into both sides because it must put everything in order. Quickselect throws one side away. That is why it does less work than sorting.
A Simple Implementation
The version below builds new lists so the logic is easy to see. The next chapter replaces it with 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)) # 3The function needs no separate base case for a one-element list. If items is [x], then pivots is [x] and lows is empty. For k == 0 the second test passes, so the function returns x.
Why k Changes When You Go Right
When you recurse into lows, the answer's rank inside lows equals its rank in the whole list, because nothing smaller was thrown away. When you recurse into highs, you throw away len(lows) + len(pivots) elements that are all smaller than the answer. Its rank inside highs drops by that amount, so you subtract it from k.
Forgetting this subtraction is the most common bug in hand-written quickselect. The code still runs but returns the wrong element, or it crashes when k exceeds the size of the sublist.
Tracing an Example
Find k = 2 in [9, 1, 8, 2, 7, 3]. The sorted list is [1, 2, 3, 7, 8, 9], so the answer is 3. Pivots are random, so your run may differ. Here is one possible sequence:
| Call | items | k | pivot | lows | pivots | highs | Decision |
|---|---|---|---|---|---|---|---|
| 1 | `[9, 1, 8, 2, 7, 3]` | 2 | 7 | `[1, 2, 3]` | `[7]` | `[9, 8]` | 2 < 3, go left |
| 2 | `[1, 2, 3]` | 2 | 2 | `[1]` | `[2]` | `[3]` | 2 ≥ 2, go right with k = 0 |
| 3 | `[3]` | 0 | 3 | `[]` | `[3]` | `[]` | 0 < 1, return 3 |
The first call discarded three elements, [7, 9, 8], and the second discarded two more. Every pivot choice ends with the same answer. Only the number of calls changes.
Common Errors
- Mixing 0-based and 1-based k.
quickselect_simple(items, 1)returns the second smallest element. To find the median of an odd-length list, passlen(items) // 2. - Dropping equal elements. If you split only into
< pivotand>= pivot, a list of identical values can recurse forever. Keep a separatepivotsgroup, or make sure the pivot is removed from the group you recurse into. - Out-of-range k. With an invalid
k, the function eventually recurses into an empty list, andrandom.choiceraisesIndexError. Check0 <= k < len(items)at the entry point if callers might pass bad values. - Assuming the input is untouched. This version leaves
itemsunchanged. In-place versions reorder the list. Know which one you are calling.
Exercise
You call quickselect_simple([4, 4, 1, 6, 4, 2], 4) and the first pivot chosen is 4. Give the sizes of lows, pivots, and highs, say which branch runs, and give the k for any recursive call. What is the final answer?
Show answer
lows = [1, 2] (size 2), pivots = [4, 4, 4] (size 3), highs = [6] (size 1). Since 4 is not less than 2 and not less than 2 + 3 = 5 is false (4 < 5 is true), the second test passes and the function returns 4 without recursing. The sorted list is [1, 2, 4, 4, 4, 6], and index 4 holds 4.
Exercise
Write a function kthlargest(items, k) that returns the k-th largest element (0-based, so k = 0 is the maximum) using quickselectsimple and no other changes.
Show answer
The k-th largest element is the (n - 1 - k)-th smallest. So: def kthlargest(items, k): return quickselectsimple(items, len(items) - 1 - k). For example, kth_largest([9, 1, 8, 2, 7, 3], 0) returns 9.