Sub topic 4
An In-Place Iterative Implementation
This chapter assumes you already know how Lomuto partitioning works and how quickselect recurses into only one side of the pivot. You should also be comfortable with Python list indexing and slicing. The list-building version from the previous chapter is easy to read, but every call allocates three new lists. Here you will turn it into a loop that works on a single array, uses O(1) extra memory, and never hits Python's recursion limit.
From Recursion to a Loop
Quickselect makes at most one recursive call per step, and that call is the last thing the function does. A function with this shape (called tail recursion) can always become a loop. The only state that changes between calls is the part of the array still under consideration. Instead of passing a new sublist, we track two indices, lo and hi, that mark the active range a[lo..hi].
Each pass through the loop does three things:
- Partition
a[lo..hi]around a random pivot and get the pivot's final indexp. - If
p == k, the pivot is the answer. - Otherwise, shrink the range to the side that contains index
k.
The Invariant
The loop depends on one invariant, which is a condition that holds at the start of every iteration:
lo <= k <= hi, and every element at an index outsidea[lo..hi]is already on the correct side of positionk.
Partitioning puts the pivot at the exact index it would have in sorted order. Everything left of p is smaller and everything right of p is at least as large. If k < p, the answer must be at an index from lo to p - 1, so we set hi = p - 1. If k > p, we set lo = p + 1. In both cases k stays inside the range, so the range can never become empty. When it shrinks to one element, that element is at index k and is the answer.
The Implementation
import random
def partition(a, lo, hi, p):
"""Lomuto partition of a[lo..hi] around a[p]; returns the pivot's final index."""
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = 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]
return store
def quickselect(a, k):
"""Return the k-th smallest element (0-based) of list a, reordering a in place."""
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
while True:
if lo == hi:
return a[lo]
p = partition(a, lo, hi, random.randint(lo, hi))
if k == p:
return a[k]
elif k < p:
hi = p - 1
else:
lo = p + 1
print(quickselect([9, 1, 8, 2, 7, 3], 2)) # 3The range check at the top is needed. Without it, an out-of-range k would break the invariant before the loop starts. The loop could then shrink past k or index outside the list, giving an error or a wrong answer that is hard to trace back to the bad argument. An empty list fails the same check, because no k satisfies 0 <= k < 0.
A Worked Trace
Take a = [9, 1, 8, 2, 7, 3] and k = 4. The sorted array is [1, 2, 3, 7, 8, 9], so the answer is 8. The pivots are random, so this trace fixes one possible sequence of choices.
| Step | lo..hi | Pivot value | Array after partition | p | Action |
|---|---|---|---|---|---|
| 1 | 0..5 | 3 | [1, 2, 3, 9, 7, 8] | 2 | k > p, so lo = 3 |
| 2 | 3..5 | 7 | [1, 2, 3, 7, 8, 9] | 3 | k > p, so lo = 4 |
| 3 | 4..5 | 8 | [1, 2, 3, 7, 8, 9] | 4 | k == p, return 8 |
Each step discards one side of the pivot, and the discarded side is never touched again.
Common Errors
- Off-by-one when shrinking. Writing
hi = porlo = pinstead ofp - 1andp + 1keeps the pivot in the range. If the same pivot is chosen again, the loop makes no progress. - Forgetting that the input is modified. The function reorders the caller's list.
- Using
random.randint(0, len(a) - 1). The pivot must come from the active rangelo..hi, not the whole array.
Testing Against Sorting
A randomized test that compares the result with sorted(data)[k] catches most indexing bugs. Add this to the same file:
def check(trials=2000):
for _ in range(trials):
n = random.randint(1, 30)
data = [random.randint(0, 20) for _ in range(n)]
k = random.randrange(n)
assert quickselect(data[:], k) == sorted(data)[k], (data, k)
print("all passed")
check()The small value range (0 to 20) produces many duplicates on purpose. The Lomuto version still gives correct results with duplicates. A later chapter explains why it slows down when many keys are equal.
Space Usage
The loop needs only a few integer variables, so its extra space is O(1). A recursive in-place version uses one stack frame per step. That is O(log n) frames on average and O(n) in the worst case, and in Python the worst case can raise RecursionError once the depth passes about 1000.
Exercise
The loop never checks whether lo > hi. Explain why the range a[lo..hi] can never become empty.
Show answer
The invariant lo <= k <= hi holds on entry because of the range check. When k < p, the new hi is p - 1, which is still at least k. When k > p, the new lo is p + 1, which is still at most k. So k always stays inside the range, the range always has at least one element, and once lo == hi that element is at index k.
Exercise
Change quickselect so it returns the index where the k-th smallest element ends up, not its value. What does the function return, and what does that index say about the array?
Show answer
Return lo in the lo == hi branch and p in the k == p branch. Both are equal to k, so the function always returns k. After the call, a[k] holds the k-th smallest element, every element before index k is less than or equal to it, and every element after index k is greater than or equal to it.