Sub topic 2
Partitioning an Array Around a Pivot
Partitioning does most of the work in quicksort. The recursion only decides which ranges to sort next. The partition step moves the elements so that the recursion has something useful to work on. This chapter defines what a correct partition is, separate from any particular way of computing one. With that definition, you can check every partition scheme in later chapters against the same rule.
This chapter assumes you can write Python, reason about array indices, follow recursive calls, and read Big-O notation. It also assumes you have seen the divide-and-conquer outline of quicksort from the previous chapter.
What partitioning promises
A pivot is one element chosen from the range being sorted. Partitioning rearranges that range so that every element smaller than the pivot comes before it and every element larger comes after it.
Stated precisely for an inclusive range a[lo..hi], a partition returns an index p with lo <= p <= hi such that:
a[p]holds the pivot value.- Every
a[i]withlo <= i < psatisfiesa[i] <= a[p]. - Every
a[i]withp < i <= hisatisfiesa[i] >= a[p]. - The range holds the same multiset of values as before. Nothing is lost, duplicated, or brought in from outside
lo..hi.
Partitioning does not promise that either side is sorted. The left side can be in any order, and so can the right side. Partitioning separates the elements. It does not sort them.
Why this is enough to sort
Conditions 2 and 3 imply that the pivot is already at its final sorted position. Exactly p - lo elements in the range are less than or equal to it and placed before it. In any sorted arrangement of the range, a value with that many elements before it belongs at index p. So after one partition, one element is finished, and no element ever needs to cross from one side to the other. The left side can be sorted on its own and the right side can be sorted on its own. That independence is what makes the recursion correct.
A reference partition you can trust
Before writing a clever in-place version, it helps to have a slow, obviously correct one. The function below copies the elements and returns a new list together with the pivot's index. It is not the version quicksort uses, but it makes a good test oracle, meaning a trusted implementation whose output you compare against.
def partition_copy(xs, pivot_index):
"""Return (new_list, p): a partition of xs around xs[pivot_index]."""
pivot = xs[pivot_index]
rest = xs[:pivot_index] + xs[pivot_index + 1:]
left = [x for x in rest if x <= pivot]
right = [x for x in rest if x > pivot]
return left + [pivot] + right, len(left)
def is_partitioned(a, lo, hi, p):
"""Check conditions 1-3 on the inclusive range a[lo..hi]."""
if not (lo <= p <= hi):
return False
pivot = a[p]
left_ok = all(a[i] <= pivot for i in range(lo, p))
right_ok = all(a[i] >= pivot for i in range(p + 1, hi + 1))
return left_ok and right_ok
data = [5, 3, 8, 1, 9, 2]
result, p = partition_copy(data, len(data) - 1) # pivot is the last element, 2
print(result, p) # [1, 2, 5, 3, 8, 9] 1
print(is_partitioned(result, 0, len(result) - 1, p)) # True
print(result[p] == sorted(data)[p]) # True: the pivot is in its final placeThe right side [5, 3, 8, 9] is not sorted, and that is fine. The only claims are that 2 sits at index 1 and that everything around it is on the correct side.
partition_copy sends elements equal to the pivot to the left. Sending them right would be just as valid, because conditions 2 and 3 both allow equality. As later chapters show, the way a scheme handles equal keys has a large effect on performance even though it has no effect on correctness.
How in-place partitioning works: regions and invariants
Real quicksort partitions in place. It rearranges the elements by swapping them within the original array and uses only O(1) extra space. Every in-place scheme follows the same pattern. It splits the range into regions whose contents are known and grows those regions until no unknown region is left. The property that holds at every step is called the loop invariant.
A typical layout during a left-to-right scan with the pivot parked at hi looks like this:
| Region | Indices | What is known |
|---|---|---|
| Small | `lo .. i-1` | every value is less than the pivot (or at most the pivot) |
| Large | `i .. j-1` | every value is at least the pivot |
| Unscanned | `j .. hi-1` | nothing yet |
| Pivot | `hi` | the pivot value |
Each step examines a[j] and, if necessary, makes one swap to extend either the small region or the large region by one element. When the unscanned region is empty, a final swap moves the pivot to the boundary between the small and large regions. The four regions have then become exactly the four conditions above. The next chapter turns this layout into the Lomuto scheme. The Hoare scheme, covered later, grows a small region from the left and a large region from the right at the same time.
Two kinds of partition contract
Partition functions return one of two kinds of result, and mixing them up is a common source of bugs.
| Contract | Returned index means | Recursive ranges | Used by |
|---|---|---|---|
| Pivot placement | `a[p]` is the pivot, in its final position | `lo..p-1` and `p+1..hi` | Lomuto, the reference above |
| Split point | every element of `lo..p` is at most every element of `p+1..hi` | `lo..p` and `p+1..hi` | Hoare |
With the pivot-placement contract, the recursion can exclude index p. With the split-point contract it cannot, because the pivot may not be at p. If you use one contract's recursive ranges with the other contract's partition, quicksort either recurses forever or leaves the array unsorted.
Edge cases a partition must survive
| Input range | Correct outcome | What goes wrong in a careless implementation |
|---|---|---|
| One element (`lo == hi`) | `p = lo`, no swaps | Reads past `hi` or past the start of the range |
| Pivot is the minimum | `p = lo`, left side empty | Off-by-one at the boundary |
| Pivot is the maximum | `p = hi`, right side empty | Off-by-one at the boundary |
| All values equal | Any `p` is valid | Always returns `lo` or `hi`, so the split is maximally lopsided |
| Many duplicates of the pivot | Duplicates may go to either side | Strict comparisons in both directions can make a scan run past the end |
The all-equal case deserves attention. It is correct for every scheme. With some schemes, though, it produces a split of 0 and n−1 elements on every call, which makes quicksort quadratic. Later chapters fix this with three-way partitioning.
Testing a partition against the specification
Because the specification is exact, you can test any partition function with random inputs. The harness below checks the reference implementation. Later you can swap in an in-place scheme by adapting the call.
import random
from collections import Counter
def partition_copy(xs, pivot_index):
pivot = xs[pivot_index]
rest = xs[:pivot_index] + xs[pivot_index + 1:]
left = [x for x in rest if x <= pivot]
right = [x for x in rest if x > pivot]
return left + [pivot] + right, len(left)
def is_partitioned(a, lo, hi, p):
if not (lo <= p <= hi):
return False
pivot = a[p]
return (all(a[i] <= pivot for i in range(lo, p)) and
all(a[i] >= pivot for i in range(p + 1, hi + 1)))
for trial in range(10_000):
n = random.randint(1, 12)
xs = [random.randint(0, 4) for _ in range(n)] # small value range forces duplicates
k = random.randrange(n)
out, p = partition_copy(xs, k)
assert Counter(out) == Counter(xs), "multiset changed"
assert out[p] == xs[k], "pivot value not at p"
assert is_partitioned(out, 0, n - 1, p), "ordering condition violated"
assert out[p] == sorted(xs)[p], "pivot not in a valid final position"
print("all partition checks passed")Drawing values from a small range such as 0 to 4 matters. With distinct values you would almost never exercise the duplicate handling, and duplicate handling is where partition bugs tend to hide.
Exercises
Exercise
The range [4, 7, 1, 4, 6, 2] is rearranged into [2, 1, 4, 4, 7, 6] and the function returns p = 3. Does this satisfy the pivot-placement contract with pivot value 4? Is p = 2 also valid for this arrangement?
Show answer
Yes. a[3] = 4, every element of a[0..2] = [2, 1, 4] is at most 4, and every element of a[4..5] = [7, 6] is at least 4. p = 2 is also valid. a[2] = 4, a[0..1] = [2, 1] is at most 4, and a[3..5] = [4, 7, 6] is at least 4. When the pivot value is duplicated, more than one index can satisfy the contract.
Exercise
A student pairs a Hoare-style partition, which returns a split point, with the recursion quicksort(a, lo, p - 1) and quicksort(a, p + 1, hi). Explain what can go wrong.
Show answer
A split-point partition does not guarantee that a[p] is in its final position. Leaving index p out of both recursive calls can therefore leave a misplaced element at p, and the array may end up unsorted. With a split point, the recursion must cover lo..p and p+1..hi.
Exercise
Why does the random test harness use values from 0 to 4 instead of 0 to 1,000,000? Name one bug that only the small range is likely to find.
Show answer
A small value range produces many duplicates, including duplicates of the pivot. A partition that uses strict comparisons such as "while a[i] < pivot" and "while a[j] > pivot" without a bounds check, or that mishandles elements equal to the pivot, can run out of the range or loop forever on equal keys. With a large value range, duplicates are rare and the bug almost never shows up.