Sub topic 2
Partitioning Around a Pivot
This chapter assumes you can read Python functions and loops, use zero-based list indexing, and follow a short proof by invariant. You do not need to know quicksort. Quickselect is built on one operation called partitioning. This chapter covers that operation by itself, so the next chapter can use it without stopping to explain it.
What partitioning does
To partition a slice a[lo..hi] around a pivot value, you rearrange the slice so that:
- every element smaller than the pivot comes before it,
- every element greater than or equal to the pivot comes after it,
- the pivot sits at an index
pbetween those two groups.
The two groups stay unsorted inside themselves. Even so, the pivot ends up at index p, which is exactly where it would be if you sorted the whole slice. That one fact is what quickselect depends on. After a single pass, you know the exact rank of one element, and you know which side holds every other element.
Lomuto partitioning
Lomuto's scheme is the simplest partition to get right. It first moves the pivot to the end of the slice. It then scans from left to right and keeps a boundary index, store. Everything to the left of store is known to be smaller than the pivot.
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] # park the pivot at the end
pivot = a[hi]
store = lo
for i in range(lo, hi): # hi is excluded: it holds the pivot
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store] # drop the pivot into its final slot
return store
a = [9, 1, 8, 2, 7, 3]
p = partition(a, 0, len(a) - 1, 5)
print(a, p) # [1, 2, 3, 9, 7, 8] 2The invariant
At the start of each loop iteration, the slice is divided into four regions:
| Region | Contents |
|---|---|
| `a[lo:store]` | elements `< pivot` |
| `a[store:i]` | elements `>= pivot` |
| `a[i:hi]` | not yet examined |
| `a[hi]` | the pivot |
When a[i] < pivot, swapping it with a[store] moves it to the end of the "smaller" region. The element it trades places with, which is either >= pivot or a[i] itself, stays in the "greater or equal" region. Advancing store and i then restores the invariant. When the loop ends, the unexamined region is empty. The final swap puts the pivot between the two groups. store then equals the number of elements smaller than the pivot, so it is the pivot's sorted index.
A traced example
Here is the run above, using a = [9, 1, 8, 2, 7, 3] with the pivot 3, which is already at hi = 5:
| `i` | `a[i]` | action | array after | `store` |
|---|---|---|---|---|
| 0 | 9 | none | `[9, 1, 8, 2, 7, 3]` | 0 |
| 1 | 1 | swap 0,1 | `[1, 9, 8, 2, 7, 3]` | 1 |
| 2 | 8 | none | `[1, 9, 8, 2, 7, 3]` | 1 |
| 3 | 2 | swap 1,3 | `[1, 2, 8, 9, 7, 3]` | 2 |
| 4 | 7 | none | `[1, 2, 8, 9, 7, 3]` | 2 |
| end | swap 2,5 | `[1, 2, 3, 9, 7, 8]` | 2 |
The pivot 3 lands at index 2. That is where it sits in the sorted list [1, 2, 3, 7, 8, 9].
Testing the postcondition
Code like this tends to fail on an off-by-one error, so test it against the definition with a quick randomized check:
import random
def partition(a, lo, hi, p):
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
for _ in range(10_000):
n = random.randint(1, 12)
a = [random.randint(0, 5) for _ in range(n)]
original = sorted(a)
q = partition(a, 0, n - 1, random.randint(0, n - 1))
assert sorted(a) == original # no elements lost
assert all(x < a[q] for x in a[:q])
assert all(x >= a[q] for x in a[q + 1:])
assert original[q] == a[q] # pivot is at its sorted index
print("ok")Common errors
- Looping to
hiinclusive. Writingrange(lo, hi + 1)compares the pivot with itself and can move it out ofa[hi]before the final swap. - Skipping the initial swap. If the pivot is not parked at
hi, the scan can move it, and the final swap then places the wrong value. - Returning before the final swap. At that point
storeis only the boundary of the "smaller" region. The pivot has not been placed yet. - Mixing up Hoare and Lomuto. Hoare's scheme does fewer swaps, but it returns a split point, not the pivot's final index. Quickselect code that expects "the pivot is at
p" breaks if you drop in Hoare's version unchanged. - Using
<=instead of<. The result is still a valid partition, with equal elements going left instead. Neither choice helps when many values are equal. If every element equals the pivot, the pivot lands at one end of the slice, so the split is completely lopsided. A later chapter fixes this with three-way partitioning.
Exercise
Partition [4, 7, 2, 9, 1] with lo = 0, hi = 4, and pivot index p = 0. What is the final array, and what index is returned?
Show answer
The first swap gives [1, 7, 2, 9, 4] with pivot 4. The scan moves 1 (store becomes 1) and 2 (swapped with 7, store becomes 2), giving [1, 2, 7, 9, 4]. The final swap of indices 2 and 4 gives [1, 2, 4, 9, 7]. The function returns 2.
Exercise
Using the invariant, explain why the returned index equals the number of elements in a[lo..hi] that are smaller than the pivot, measured from lo.
Show answer
store starts at lo and goes up by exactly one each time the scan finds an element smaller than the pivot. No other step changes it. After the loop, store - lo is the count of smaller elements. The final swap puts the pivot at store, directly after all of them.