Sub topic 2
Partitioning Around a Pivot
Quickselect is fast because of one operation: partitioning. Partitioning rearranges part of an array around a chosen value, the pivot, so that smaller elements end up on its left and the rest end up on its right. Once that is done, the pivot is at the index it would have if the array were fully sorted. This chapter covers the partition step in detail, before the next chapter uses it to build quickselect.
This chapter assumes you can read Python functions, loops, and list indexing, that you are comfortable with zero-based indices, and that you know what O(n) means. Familiarity with quicksort helps, because quicksort uses the same partition routine, but it is not required.
What a Partition Guarantees
A partition routine takes an array a, a subrange a[lo..hi] (both ends inclusive), and the index p of a pivot inside that range. It returns an index q and leaves the subrange in this state:
- Every element in
a[lo..q-1]is less than the pivot. a[q]holds the pivot.- Every element in
a[q+1..hi]is greater than or equal to the pivot.
That is the postcondition: the property the caller can rely on after the call returns. It has a consequence that quickselect depends on. If exactly q - lo elements are smaller than the pivot, then the pivot is the (q - lo)-th smallest element of the subrange, counting from zero. The pivot is in its final sorted position, even though neither side is sorted.
Partitioning does much less work than sorting. It makes one pass over the range, performs O(n) comparisons, and uses O(1) extra memory. A comparison sort needs Ω(n log n) comparisons in the worst case. Quickselect gets most of its speed from this difference.
Lomuto Partitioning
Lomuto partitioning (named after Nico Lomuto, popularized by Jon Bentley's Programming Pearls) is the simplest in-place scheme to get right. It works in three steps:
- Swap the pivot to the end of the range,
a[hi], so it stays out of the way while the scan runs. - Scan
ifromlotohi - 1. Keep a boundarystoremarking where the next "small" element belongs. Whenevera[i] < pivot, swap it into positionstoreand advancestore. - Swap the pivot from
a[hi]intoa[store]. Returnstore.
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
data = [9, 1, 8, 2, 7, 3]
q = partition(data, 0, len(data) - 1, random.randint(0, len(data) - 1))
print(q, data[q], data)Each run picks a random pivot, so the output changes from run to run. In every run, the elements left of data[q] are smaller and the elements to its right are at least as large.
The routine receives the pivot's index p rather than picking one itself. That keeps pivot choice (random, first element, median-of-three) separate from the mechanics of partitioning. A later chapter covers pivot strategies.
The Loop Invariant
An invariant is a statement that holds at the start of every loop iteration. Lomuto's correctness follows from this one. At the top of each iteration, with scan index i:
| Region | Contents |
|---|---|
| `a[lo .. store-1]` | elements strictly less than the pivot |
| `a[store .. i-1]` | elements greater than or equal to the pivot |
| `a[i .. hi-1]` | not yet examined |
| `a[hi]` | the pivot |
Here is why the invariant keeps holding:
- Initialization. Before the first iteration,
store == i == lo. The first two regions are empty, so the claims about them are trivially true. - Maintenance. If
a[i] >= pivot, the loop only advancesi, which extends the "at least pivot" region by one correctly classified element. Ifa[i] < pivot, swapping it witha[store]places a small element at the end of the "less than" region. The element it displaces was the first member of the "at least pivot" region (ora[i]itself, if that region was empty), and it moves to positioni, the new end of that region. Advancing bothstoreandirestores the invariant. - Termination. When
i == hi, nothing is left unexamined. The final swap moves the pivot tostore, between the two regions, and that gives the postcondition.
Reasoning about the regions also helps with debugging. If you know which region every index is in, you can check each line of the loop against the table.
A Worked Trace
Partition [9, 1, 8, 2, 7, 3] with lo = 0, hi = 5, and the pivot at index 5 (value 3), so step 1's swap does nothing.
| Step | `i` | `a[i]` | Action | Array after step | `store` |
|---|---|---|---|---|---|
| start | `[9, 1, 8, 2, 7, 3]` | 0 | |||
| 1 | 0 | 9 | 9 ≥ 3, skip | `[9, 1, 8, 2, 7, 3]` | 0 |
| 2 | 1 | 1 | 1 < 3, swap a[0], a[1] | `[1, 9, 8, 2, 7, 3]` | 1 |
| 3 | 2 | 8 | 8 ≥ 3, skip | `[1, 9, 8, 2, 7, 3]` | 1 |
| 4 | 3 | 2 | 2 < 3, swap a[1], a[3] | `[1, 2, 8, 9, 7, 3]` | 2 |
| 5 | 4 | 7 | 7 ≥ 3, skip | `[1, 2, 8, 9, 7, 3]` | 2 |
| final | swap a[2], a[5] | `[1, 2, 3, 9, 7, 8]` | 2 |
The routine returns 2. Two elements are smaller than 3, so 3 is the element at index 2 of the sorted array, the third smallest. The right side [9, 7, 8] is not sorted, and partitioning doesn't need it to be.
The following instrumented version prints the same trace, so you can try it on your own inputs:
def partition_traced(a, lo, hi, p):
"""Lomuto partition that prints the regions after each step."""
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = lo
print(f"pivot={pivot} start {a[lo:hi + 1]}")
for i in range(lo, hi):
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
print(f"i={i} less={a[lo:store]} geq={a[store:i + 1]} "
f"rest={a[i + 1:hi]} pivot={a[hi]}")
a[store], a[hi] = a[hi], a[store]
print(f"final {a[lo:hi + 1]} -> pivot index {store}")
return store
partition_traced([9, 1, 8, 2, 7, 3], 0, 5, 5)Verifying the Postcondition
Partition bugs tend to show up only on certain inputs: duplicates, ranges of length one, or pivots already at an edge. A randomized property test finds them quickly. The test below checks four properties:
- The returned index lies within the range.
- The postcondition holds.
- Elements outside
a[lo..hi]are untouched. - The pivot is at its sorted position within the subrange.
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
def is_partitioned(a, lo, hi, q):
pivot = a[q]
left_ok = all(a[i] < pivot for i in range(lo, q))
right_ok = all(a[i] >= pivot for i in range(q + 1, hi + 1))
return left_ok and right_ok
for _ in range(10_000):
n = random.randint(1, 20)
a = [random.randint(0, 9) for _ in range(n)]
lo = random.randint(0, n - 1)
hi = random.randint(lo, n - 1)
p = random.randint(lo, hi)
outside_before = a[:lo] + a[hi + 1:]
sub_sorted = sorted(a[lo:hi + 1])
q = partition(a, lo, hi, p)
assert lo <= q <= hi
assert is_partitioned(a, lo, hi, q)
assert a[:lo] + a[hi + 1:] == outside_before
assert sorted(a[lo:hi + 1]) == sub_sorted # same multiset
assert sub_sorted[q - lo] == a[q] # pivot in sorted position
print("all checks passed")The last assertion is the property quickselect relies on. Values drawn from 0 to 9 guarantee many duplicates, which is where off-by-one mistakes in comparisons usually show up.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting to swap the pivot to `a[hi]` first | Pivot gets moved during the scan; wrong final index | Always do `a[p], a[hi] = a[hi], a[p]` before reading `pivot` |
| Looping `range(lo, hi + 1)` | Pivot compares against itself and may be swapped mid-scan | Scan only `lo .. hi-1`; the pivot is handled by the final swap |
| Skipping the final swap | Returned index holds a non-pivot value | Swap `a[store]` and `a[hi]` before returning |
| Using `range(len(a))` or starting `store = 0` | Corrupts elements outside the subrange on recursive calls | Use `lo` and `hi` everywhere, never 0 and `len(a)` |
| Returning an index relative to the subrange | Caller compares `q` with an absolute `k` and recurses into the wrong side | Return absolute positions; Lomuto's `store` already is one |
| Treating the right side as "greater than" | Logic errors when duplicates of the pivot exist | Remember the right side is "greater than or equal" |
Edge Cases
A range of length one. With lo == hi, the loop body never runs, both swaps exchange a[hi] with itself, and the routine returns lo. Quickselect usually returns before calling partition in this case, but the routine is still safe.
The pivot is the minimum. No element is smaller, so store stays at lo and the pivot moves to the front. The right side has hi - lo elements. The pass removed only one element from consideration.
The pivot is the maximum. Every other element is smaller, so store reaches hi and the pivot stays at the end. Again, only one element is removed.
All elements equal. Every comparison a[i] < pivot is false, so the pivot lands at lo every time, as if it were the minimum. This is the duplicate problem. On an array of identical values, every partition peels off a single element. A selection algorithm that keeps partitioning the larger side then performs about n²/2 comparisons, no matter how the pivot is chosen. A later chapter fixes this with three-way partitioning, which groups all copies of the pivot into a middle block.
Already sorted input with a fixed pivot. If the caller always passes p = hi on sorted data, the pivot is always the maximum, which is the bad case above. The partition routine is not at fault here. The pivot choice is, which is why the routine takes p as a parameter.
Lomuto Versus Hoare
Lomuto is not the only in-place scheme. Tony Hoare's original partition uses two indices that start at opposite ends and move toward each other, swapping pairs that are on the wrong side.
def hoare_partition(a, lo, hi):
"""Hoare partition of a[lo..hi] (requires lo < hi) around its middle element.
Returns j with lo <= j < hi such that every element of a[lo..j]
is <= every element of a[j+1..hi]."""
pivot = a[(lo + hi) // 2]
i, j = lo - 1, hi + 1
while True:
i += 1
while a[i] < pivot:
i += 1
j -= 1
while a[j] > pivot:
j -= 1
if i >= j:
return j
a[i], a[j] = a[j], a[i]
data = [9, 1, 8, 2, 7, 3]
j = hoare_partition(data, 0, len(data) - 1)
print(j, data[:j + 1], data[j + 1:]) # 2 [3, 1, 2] [8, 7, 9]| Property | Lomuto | Hoare |
|---|---|---|
| Swaps on random input | about n/2 | about n/6 |
| Pivot ends in its final sorted position | yes | not necessarily |
| Return value | pivot's index | a split point between two halves |
| Behavior when all keys are equal | pivot ends at `lo`, maximally unbalanced split | splits near the middle |
| Ease of getting right | simpler | stricter index conditions |
Hoare's scheme does fewer swaps and handles equal keys better, because both scans stop on elements equal to the pivot and swap them. The cost is a weaker postcondition. The returned j only separates two halves, and the pivot may lie on either side. Quickselect built on Hoare cannot check whether the returned index equals k. It has to keep narrowing until the range has one element. This tutorial uses Lomuto for its clearer guarantee, and uses three-way partitioning when duplicates matter.
Exercise
Trace Lomuto partitioning on [4, 7, 2, 4, 1] with lo = 0, hi = 4, and p = 0 (pivot value 4). Give the final array and the returned index.
Show answer
Swapping a[0] with a[4] gives [1, 7, 2, 4, 4], pivot = 4, store = 0. At i=0, 1 < 4, so a[0] swaps with itself and store becomes 1. At i=1, 7 is not less than 4, so the loop skips it. At i=2, 2 < 4, so a[1] and a[2] swap, giving [1, 2, 7, 4, 4], and store becomes 2. At i=3, 4 is not less than 4, so the loop skips it. The final swap of a[2] and a[4] gives [1, 2, 4, 4, 7]. The routine returns 2. The duplicate 4 sits on the right side, which allows values greater than or equal to the pivot.
Exercise
A colleague writes for i in range(lo, hi + 1): in Lomuto's loop and says tests still pass on small arrays of distinct values. Explain what actually happens when i reaches hi, and why the bug can still produce a wrong answer.
Show answer
At i = hi, the loop compares the pivot with itself. Since pivot < pivot is false, nothing is swapped, and the result is still correct with the strict comparison. The bug becomes visible if the comparison is <=. Then the pivot is swapped into a[store] during the loop, store is incremented, and the final swap of a[store] and a[hi] moves an element greater than the pivot into the last position. The returned index then no longer holds the pivot. The extra iteration is wasted work at best, and it can break the postcondition when combined with another small change.
Exercise
Using Lomuto partitioning on an array of n identical values, how many elements does each call remove from consideration, and roughly how many comparisons does repeatedly partitioning the larger remaining side cost in total?
Show answer
Each call places the pivot at lo and leaves the other hi - lo elements on the right, so it removes one element. Repeating on the larger side costs (n-1) + (n-2) + ... + 1, about n²/2 comparisons, which is quadratic. Three-way partitioning fixes this by grouping all copies of the pivot into one middle block.