Sub topic 11
The Hoare Partition Scheme
This chapter assumes you have read the chapters on partitioning and the Lomuto scheme. It also assumes you can follow a recursive function in Python and know what O(n) means. Lomuto's scheme is easy to reason about because the pivot lands at its final index. Hoare's original 1961 scheme gives up that property. In exchange it does fewer swaps and handles duplicate keys much better. The price is that the recursion bounds differ, and getting them wrong is the most common way to break it.
How Hoare's Scheme Works
Hoare partitioning moves two indices toward each other from opposite ends of the range:
- Pick a pivot value. Here it is the element at the middle index.
- Move
iright until it finds an element that is greater than or equal to the pivot. That element belongs on the right side. - Move
jleft until it finds an element that is less than or equal to the pivot. That element belongs on the left side. - If
iandjhave not crossed, swap the two misplaced elements and repeat. - When they meet or cross, return
j.
When the function returns p = j, it guarantees one thing. Every element in a[lo..p] is less than or equal to the pivot, and every element in a[p+1..hi] is greater than or equal to it. The function does not guarantee that the pivot sits at index p. The pivot may be anywhere, and it may even have been swapped to the far end of the range.
The Implementation
import random
def hoare_partition(a, lo, hi):
pivot = a[(lo + hi) // 2]
i = lo - 1
j = 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]
def quicksort_hoare(a, lo, hi):
if lo < hi:
p = hoare_partition(a, lo, hi)
quicksort_hoare(a, lo, p)
quicksort_hoare(a, p + 1, hi)
data = [5, 3, 8, 1, 9, 2]
quicksort_hoare(data, 0, len(data) - 1)
print(data) # [1, 2, 3, 5, 8, 9]
# Randomized check against Python's built-in sort
for _ in range(1000):
xs = [random.randint(0, 20) for _ in range(random.randint(0, 30))]
ys = xs[:]
quicksort_hoare(ys, 0, len(ys) - 1)
assert ys == sorted(xs)
print("all tests passed")The indices start one step outside the range (lo - 1 and hi + 1) because each pass increments or decrements before testing. This is how Python expresses the "do-while" loop from Hoare's original description.
A Worked Trace
Partition [5, 3, 8, 1, 9, 2] with lo = 0 and hi = 5. The middle index is 2, so the pivot is 8.
| Step | i stops at | j stops at | Action | Array after |
|---|---|---|---|---|
| 1 | 2 (value 8) | 5 (value 2) | swap | [5, 3, 2, 1, 9, 8] |
| 2 | 4 (value 9) | 3 (value 1) | i >= j, return 3 | [5, 3, 2, 1, 9, 8] |
The function returns p = 3. The left part a[0..3] is [5, 3, 2, 1], and every value in it is at most 8. The right part a[4..5] is [9, 8], and every value in it is at least 8. The pivot 8 ended up at index 5, not at index 3. This is why the recursion has to include index p in the left call. Unlike Lomuto, Hoare does not place an element at its final position during partitioning.
Why the Recursion Bounds Are `lo..p` and `p+1..hi`
With Lomuto, the recursion is quicksort(a, lo, p - 1) and quicksort(a, p + 1, hi). Skipping p is correct there because the pivot is already in its final place. With Hoare, a[p] is just some element that is at most the pivot. Skipping it would leave it unsorted.
The two schemes therefore return different things:
| Property | Lomuto | Hoare |
|---|---|---|
| Return value `p` means | Pivot's final index | Boundary between the two sides |
| Left recursion | `lo .. p-1` | `lo .. p` |
| Right recursion | `p+1 .. hi` | `p+1 .. hi` |
| Pivot at final index after partition | Yes | Not necessarily |
| Typical pivot position | `a[hi]` | `a[(lo+hi)//2]` or `a[lo]` |
| Swaps on random input | More | About three times fewer |
| All-equal keys | O(n²), every split is maximally uneven | O(n log n), splits near the middle |
The Pivot Must Not Be `a[hi]`
Using the last element as the pivot works for Lomuto, but it breaks Hoare. Take [1, 2] with pivot = a[hi] = 2:
ipasses 1 (since 1 < 2) and stops at index 1.jstops right away at index 1, because 2 > 2 is false.i >= j, so the function returnsp = 1 = hi.
The left recursion is then quicksort_hoare(a, 0, 1), which is the same range again. Python eventually raises RecursionError.
The termination argument requires lo <= p < hi, so that both subranges are strictly smaller. That holds when the pivot index is anything other than hi. The floor midpoint (lo + hi) // 2 is always less than hi when lo < hi, so it is safe. a[lo] is also safe. If you want a random pivot, choose its index from lo to hi - 1, or swap the random element into position lo.
Why the Scans Stay in Bounds
The inner loops while a[i] < pivot and while a[j] > pivot have no explicit bounds check, yet they never run off the array. On the first pass, the pivot itself is inside the range, so both scans stop at the pivot at the latest. After a swap, a[i] holds a value <= pivot and a[j] holds a value >= pivot. Those values act as sentinels. The next j scan cannot move left past the old i, and the next i scan cannot move right past the old j.
This depends on using strict comparisons. If you change < to <=, then on an array where every element equals the pivot, i never stops and runs past hi. In Python that raises IndexError. In C it reads memory outside the array.
Duplicates: Stopping on Equal Keys
It can look wasteful that both scans stop on elements equal to the pivot and swap them. It is actually what makes Hoare's scheme handle duplicates well. On [4, 4, 4, 4], the scans stop at every element, swap pairs, and meet in the middle. The function returns p = 1, which splits the range into two halves of size 2. An array of n equal keys therefore takes O(n log n) time.
Lomuto's a[j] < pivot test is never true on such an array. Every split leaves n − 1 elements on one side, and the running time becomes O(n²). Hoare's equal-key swaps are unnecessary moves, but they keep the splits balanced. If an input has many duplicate keys, three-way partitioning (covered in a later chapter) does better than either scheme, because it removes all the equal keys in a single pass.
Common Errors
- Wrong recursion bounds. Using
p - 1for the left call dropsa[p]. - Last-element pivot.
a[hi]as pivot can returnp == hiand recurse forever. - Non-strict comparisons. Using
<=or>=in the scans lets the indices run out of bounds on equal keys. - Starting indices at
loandhi. If you keep the increment-before-test loop structure, starting atloandhiskips the first and last elements. Start one step outside the range. - Expecting the pivot at
p. Code that readsa[p]after partitioning and treats it as the pivot is wrong. Quickselect built on Hoare has to handle this case differently.
Exercise
Trace hoare_partition on [3, 7, 1, 6, 2] with lo = 0 and hi = 4. What is the pivot, what does the array look like when the function returns, and what value of p does it return?
Show answer
The middle index is 2, so the pivot is 1. In the first pass, i stops at index 0 (3 is not less than 1) and j stops at index 2 (1 is not greater than 1), so a[0] and a[2] are swapped, giving [1, 7, 3, 6, 2]. In the second pass, i stops at index 1 (7) and j moves left to index 0 (value 1). Now i >= j, so the function returns p = 0. The left part a[0..0] is [1] and the right part a[1..4] is [7, 3, 6, 2].
Exercise
A colleague changes the pivot line to pivot = a[(lo + hi + 1) // 2], which picks the upper middle. Why can this cause infinite recursion with the lo..p / p+1..hi bounds, and what is the smallest input that shows it?
Show answer
With the upper middle, when hi = lo + 1 the pivot index is hi, which is the same as choosing a[hi]. For [1, 2], the pivot is 2, i stops at index 1, j stops at index 1, and the function returns p = 1 = hi. The left call quicksort_hoare(a, 0, 1) repeats the same range forever. The pivot index must be strictly less than hi, or the recursion must change to lo..p-1 and p..hi to match.
Exercise
Explain why Hoare partitioning runs in O(n log n) on an array of n identical keys while Lomuto partitioning runs in O(n^2).
Show answer
Hoare's scans stop on elements equal to the pivot, so on identical keys i and j stop at every position, swap, and meet near the middle. Each split is roughly n/2 and n/2, which gives O(n log n). Lomuto moves an element left only when it is strictly less than the pivot, so on identical keys nothing moves and the pivot lands at lo. Each call removes only one element, which gives O(n^2).