Sub topic 2
An In-Place Iterative Implementation
This chapter assumes you know Python lists, zero-based indexing, Big-O notation, and the recursive quickselect from the previous chapter.
Replacing Recursion With a Loop
Quickselect recurses into only one side, so the recursion can become a loop. The loop tracks a window a[lo..hi] and keeps one invariant: index k always lies inside that window. Each partition puts the pivot at its final index p. If p == k, you are done. If not, the window shrinks to the side that holds k. This version uses no extra lists and no call stack.
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)) # 3Choosing a Pivot
| Strategy | Cost | Weakness |
|---|---|---|
| First element | Free | Already sorted or reverse-sorted input gives the worst case every time |
| Median-of-three (first, middle, last) | 3 comparisons | Handles sorted input, but crafted inputs can still defeat it |
| Random index | One RNG call | No fixed input is bad for it; only bad luck is |
A random pivot is the usual default because no particular input can force bad behavior.
Expected O(n), Worst-Case O(n²)
Partitioning a window of size m costs O(m). Suppose the pivot lands in the middle half of the window. Then at least a quarter of the window is discarded. A random pivot lands in the middle half with probability 1/2, so on average it takes two partitions to shrink the window by a factor of 3/4. The total work forms a geometric series, roughly n + ¾n + (¾)²n + …, which is bounded by a constant times n. That makes the expected running time O(n).
In the worst case, every pivot is the minimum or the maximum, so each step removes only one element. The work becomes n + (n−1) + … + 1 = O(n²). With a first-element pivot, a sorted array triggers this case every time.
Exercise
You call quickselect with a first-element pivot on the sorted list [1, 2, ..., n] and k = n − 1. How many partition steps run, and what is the total running time?
Show answer
Each pivot is the current minimum, so each step removes one element and the window moves up by one. About n − 1 partitions run, with sizes n, n−1, …, 2, for O(n²) total.