Sub topic 4
An In-Place Iterative Implementation
This chapter assumes you already know Lomuto partitioning and the recursive quickselect idea from the earlier chapters. You should also be comfortable with Python lists, while loops, and zero-based indexes. The goal here is a version you could ship: it works inside the caller's list, uses constant extra memory, and has no recursion that can overflow the call stack.
The list-building version from the previous chapter is easy to read, but each call allocates three new lists, and each level of recursion adds a stack frame. On a list of a million numbers this creates a lot of temporary objects. With a poor pivot sequence it can also exceed Python's recursion limit. Both problems go away once you make two changes:
- Partition the original list in place, between two boundary indexes
loandhi. - Replace the recursive call with a loop that moves
loorhi.
Quickselect makes at most one recursive call per level, and that call is the last thing the function does. That makes it tail recursive. Any tail call can become a loop iteration that updates the parameters and goes back to the top, so the conversion here is mechanical.
The Working Model: A Shrinking Window
At every point the algorithm keeps a window a[lo..hi], with both ends inclusive. It promises two things about that window:
- Window invariant:
lo <= k <= hi. The answer's final sorted position is always inside the window. - Outside invariant: every element left of
lois less than or equal to every element in the window, and every element right ofhiis greater than or equal to every element in the window.
Each partition step drops the pivot into its final sorted index p. Then one of three things happens:
| Comparison | Meaning | Window update |
|---|---|---|
| `k == p` | The pivot is the answer | Return `a[k]` |
| `k < p` | The answer is left of the pivot | `hi = p - 1` |
| `k > p` | The answer is right of the pivot | `lo = p + 1` |
If the window shrinks to a single index, the window invariant forces that index to be k, so a[lo] is the answer.
The Implementation
Save this listing as quickselect.py. The later listings import from it.
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
if __name__ == "__main__":
print(quickselect([9, 1, 8, 2, 7, 3], 2)) # 3Some details in this code are deliberate:
- The range check happens first. It rejects an empty list, a negative
k, andk >= len(a). Without it, an empty list would sethi = -1and the loop would reada[-1]or partition garbage. A negativekis worse because the code would not crash. It would return a wrong answer. random.randint(lo, hi)includes both ends. That matches the inclusive window. If you usedrandom.randrange(lo, hi),hicould never be picked, which is still correct but slightly biased.- The loop cannot run off the end. If
k < p, the newhi = p - 1is still>= k >= lo. Thek > pcase works the same way. Solo <= hialways holds, and nolo > hicheck is needed. - The loop always terminates. Each iteration either returns or removes at least the pivot from the window, so the window gets strictly smaller.
Tracing One Run
Random pivots make a trace hard to repeat. The traced variant below takes a pivot-choosing function, so you can fix the choice. Here it always uses the last element of the window.
from quickselect import partition
def quickselect_traced(a, k, choose_pivot):
lo, hi = 0, len(a) - 1
step = 0
while True:
step += 1
if lo == hi:
print(f"step {step}: lo == hi == {lo}, return {a[lo]}")
return a[lo]
p = partition(a, lo, hi, choose_pivot(lo, hi))
print(f"step {step}: window [{lo}, {hi}], pivot {a[p]} lands at {p}, a = {a}")
if k == p:
return a[k]
elif k < p:
hi = p - 1
else:
lo = p + 1
quickselect_traced([9, 1, 8, 2, 7, 3], 3, lambda lo, hi: hi)Output:
step 1: window [0, 5], pivot 3 lands at 2, a = [1, 2, 3, 9, 7, 8]
step 2: window [3, 5], pivot 8 lands at 4, a = [1, 2, 3, 7, 8, 9]
step 3: lo == hi == 3, return 7This trace uses all three branches. In step 1 the pivot lands at index 2 and k = 3 is to its right, so lo becomes 3. In step 2 the pivot lands at index 4 and k is to its left, so hi becomes 3. In step 3 the window holds one element, and it is the answer. The sorted list is [1, 2, 3, 7, 8, 9], and index 3 holds 7, which matches.
A Useful Side Effect: The List Is Partitioned Around k
When quickselect(a, k) returns, the list is in a specific state, not just a scrambled one:
a[k]holds the k-th smallest element.- Every element in
a[:k]is<= a[k]. - Every element in
a[k+1:]is>= a[k].
This follows from the outside invariant. Each partition step left all discarded elements on the correct side of the window, and the final step put the answer at index k. So the call also gives you the k smallest elements, in no particular order, at no extra cost. std::nth_element and numpy.partition, covered in a later chapter, make the same guarantee.
from quickselect import quickselect
def smallest_k(items, k):
"""Return the k smallest items (unordered) without sorting everything."""
if k <= 0:
return []
a = list(items)
if k >= len(a):
return a
quickselect(a, k - 1)
return a[:k]
print(sorted(smallest_k([40, 10, 90, 30, 70, 20, 60], 3))) # [10, 20, 30]The only sorted call here is for readable output. If you need the k items in order, sort only a[:k]. That costs O(k log k) instead of O(n log n).
Testing It Against a Reference
Off-by-one bugs in index-based code are easy to write and hard to see. Randomized testing against sorted() finds them quickly. Small lists with a narrow value range produce many duplicates and many edge cases.
import random
from quickselect import quickselect
for trial in range(5000):
n = random.randint(1, 30)
data = [random.randint(-5, 5) for _ in range(n)]
k = random.randrange(n)
expected = sorted(data)[k]
work = data[:]
got = quickselect(work, k)
assert got == expected, (data, k, got, expected)
assert sorted(work) == sorted(data), "elements were lost or duplicated"
assert work[k] == got
assert all(x <= got for x in work[:k])
assert all(x >= got for x in work[k + 1:])
for bad_k in (-1, 3):
try:
quickselect([1, 2, 3], bad_k)
except IndexError:
pass
else:
raise AssertionError(f"k={bad_k} should raise")
print("all tests passed")The second assertion catches a common class of bug. A broken swap can overwrite a value instead of exchanging it, which turns the list into something other than a permutation of the input. That bug can still return the right answer on many inputs.
Why the Loop Matters: Stack Depth
CPython's default recursion limit is 1000 frames. A recursive quickselect that gets unlucky pivots shrinks the window by only one element per call, so its depth can reach n. The script below forces that worst case: a sorted input, always pivoting on the last element, and asking for the minimum.
import sys
from quickselect import partition
def quickselect_recursive(a, k, lo, hi):
if lo == hi:
return a[lo]
p = partition(a, lo, hi, hi)
if k == p:
return a[k]
if k < p:
return quickselect_recursive(a, k, lo, p - 1)
return quickselect_recursive(a, k, p + 1, hi)
def quickselect_last_pivot(a, k):
lo, hi = 0, len(a) - 1
while True:
if lo == hi:
return a[lo]
p = partition(a, lo, hi, hi)
if k == p:
return a[k]
if k < p:
hi = p - 1
else:
lo = p + 1
n = 2000
print("recursion limit:", sys.getrecursionlimit())
try:
quickselect_recursive(list(range(n)), 0, 0, n - 1)
except RecursionError:
print("recursive version: RecursionError")
print("iterative version:", quickselect_last_pivot(list(range(n)), 0))The recursive version crashes. The iterative version returns 0. It still does about n²/2 comparisons, so the loop removes the crash but does not make the worst case fast. Random pivots make that worst case extremely unlikely, as the complexity chapter shows. Removing the recursion means that a rare bad run is merely slow and never kills the program.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using an exclusive `hi` (`len(a)`) with an inclusive partition | `IndexError` or the last element is never examined | Pick one convention. This chapter uses inclusive `hi = len(a) - 1` |
| Setting `hi = p` or `lo = p` instead of `p ± 1` | Infinite loop when the pivot keeps landing at the same index | Exclude the pivot. It is already in its final place |
| Comparing `k` with the pivot's value instead of its index `p` | Wrong answers that look plausible | `p` is a position, so compare positions |
| Passing a one-based `k` from user input | Returns the next-larger element | Convert once at the boundary with `k - 1` |
| Choosing the pivot from `0..len(a)-1` instead of `lo..hi` | Pivot outside the window, which corrupts finished regions | Always pick from the current window |
| Forgetting that the list is mutated | Caller's data appears shuffled | Document it, or copy at the call site |
Duplicates are a separate problem. With Lomuto partitioning, if every element equals the pivot, the test a[i] < pivot never succeeds. The pivot then always lands at lo, and when k is large the window shrinks by one element per iteration. That is quadratic even with random pivots. The three-way partitioning chapter fixes this.
Exercises
Exercise
Run quickselect_traced([4, 4, 4, 4, 4], 4, lambda lo, hi: hi) by hand. How many partition steps happen before it returns, and what does this tell you about Lomuto partitioning on duplicate-heavy input?
Show answer
Every comparison a[i] < 4 fails, so each partition puts the pivot at index lo. Because k = 4 > p, lo advances by one each time: p = 0, 1, 2, 3, which is 4 partition steps. On the next iteration lo == hi == 4 and the function returns 4. In general the window shrinks by one per step, giving about n²/2 comparisons, so all-equal input is a worst case for Lomuto whatever the pivot choice.
Exercise
A colleague replaces "hi = p - 1" with "hi = p" because "it is safer to keep the pivot in the window." Give an input and pivot rule on which this change causes an infinite loop.
Show answer
Use a = [1, 2] with k = 0 and a pivot rule that always picks hi. Partition puts the pivot 2 at p = 1. Since k < p, the buggy code sets hi = 1, which leaves the window [0, 1] unchanged. The same partition repeats forever. Excluding the pivot is what guarantees the window shrinks on every iteration.
Exercise
Write a function median_low(items) that returns the lower median of a non-empty list (the element at sorted index (n - 1) // 2) using quickselect without modifying the caller's list. What are its expected time and its extra memory?
Show answer
def median_low(items): return quickselect(list(items), (len(items) - 1) // 2). The copy prevents mutation of the caller's list. Expected time is O(n) with random pivots. Extra memory is O(n) for the copy and O(1) beyond that, because the iterative loop uses no recursion stack.