Hoare Partitioning
Lomuto's scheme is easy to prove correct, but it does more work than necessary: it swaps every small value it meets, even ones that are already on the correct side, and it falls apart on repeated keys. The original partition scheme, published by Tony Hoare together with quicksort in 1961, works from both ends at once. Two indices move towards each other, each stopping at a value that is on the wrong side, and then the two misplaced values swap. On random input it makes about a third as many swaps as Lomuto, and it splits arrays of equal keys evenly.
The price is subtlety. Hoare's scheme does not put the pivot in its final place, the index it returns means something different, and small changes to it (a different pivot position, <= instead of <) produce an infinite loop or an index out of bounds. This lesson goes through it carefully.
The procedure
HOARE-PARTITION(a, lo, hi) // a[lo..hi] inclusive, at least 2 elements
1 pivot = a[lo]
2 i = lo - 1, j = hi + 1
3 loop
4 repeat j = j - 1 until a[j] <= pivot // scan left for a value that belongs left
5 repeat i = i + 1 until a[i] >= pivot // scan right for a value that belongs right
6 if i < j
7 swap a[i] and a[j]
8 else
9 return jThe result is weaker than Lomuto's but enough for sorting. It returns an index with such that
The pivot itself can end up anywhere in either part, so quicksort recurses on and , both including the pivot's region, and not on "" and "" as with Lomuto.
def hoare_partition(a, lo, hi, trace=False):
pivot = a[lo]
i, j = lo - 1, hi + 1
while True:
j -= 1
while a[j] > pivot:
j -= 1
i += 1
while a[i] < pivot:
i += 1
if i < j:
if trace: print(f" i = {i} stops at {a[i]}, j = {j} stops at {a[j]}: swap")
a[i], a[j] = a[j], a[i]
if trace: print(f" {a}")
else:
if trace: print(f" i = {i}, j = {j}: the scans have crossed, return {j}")
return j
a = [6, 3, 8, 1, 9, 2, 5]
print("pivot", a[0], "in", a)
j = hoare_partition(a, 0, len(a) - 1, trace=True)
print(f"left a[0..{j}] = {a[:j + 1]}, right a[{j + 1}..6] = {a[j + 1:]}")pivot 6 in [6, 3, 8, 1, 9, 2, 5]
i = 0 stops at 6, j = 6 stops at 5: swap
[5, 3, 8, 1, 9, 2, 6]
i = 2 stops at 8, j = 5 stops at 2: swap
[5, 3, 2, 1, 9, 8, 6]
i = 4, j = 3: the scans have crossed, return 3
left a[0..3] = [5, 3, 2, 1], right a[4..6] = [9, 8, 6]
Only two swaps, against Lomuto's three swaps plus a pivot move on the same array in the previous lesson. Notice that the pivot is not at the boundary: it sits at the end of the right part, which is allowed, because is at least everything on the left.
In C++
#include <cstdio>
#include <utility>
#include <vector>
int hoare_partition(std::vector<int>& a, int lo, int hi) {
int pivot = a[lo];
int i = lo - 1, j = hi + 1;
for (;;) {
do --j; while (a[j] > pivot);
do ++i; while (a[i] < pivot);
if (i >= j) return j;
std::swap(a[i], a[j]);
}
}
void quicksort(std::vector<int>& a, int lo, int hi) {
if (lo >= hi) return;
int j = hoare_partition(a, lo, hi);
quicksort(a, lo, j); // note: j, not j - 1
quicksort(a, j + 1, hi);
}
int main() {
std::vector<int> a = {6, 3, 8, 1, 9, 2, 5};
int j = hoare_partition(a, 0, 6);
std::printf("split after index %d:", j);
for (int x : a) std::printf(" %d", x);
std::printf("\n");
std::vector<int> b = {5, 5, 1, 9, 5, 3, 5, 7, 5, 2};
quicksort(b, 0, static_cast<int>(b.size()) - 1);
std::printf("sorted:");
for (int x : b) std::printf(" %d", x);
std::printf("\n");
}split after index 3: 5 3 2 1 9 8 6
sorted: 1 2 3 5 5 5 5 5 7 9
The do … while loops in C++ are the "repeat … until" of the pseudocode: each scan moves first and tests afterwards, so after a swap both indices move past the values just exchanged.
Why it is correct
Three things must be shown: the scans never leave , the returned satisfies (so both parts are non-empty and the recursion makes progress), and the parts are ordered.
Proof sketch
First round. The scan of line 5 starts at , where the pivot itself sits, so it stops there immediately: . The scan of line 4 stops at the latest at too, because pivot. If it stops at then and the procedure returns . That is only possible when every value in is greater than the pivot, and then the split , is correct.
After a swap. When the values swap, so now pivot and pivot. These two values act as sentinels for the next round: the left-moving scan cannot pass position (it would stop there at the latest), and the right-moving scan cannot pass position . So neither index leaves the subarray.
Invariant. At the start of each round, every value in is at most the pivot and every value in is at least the pivot. The scans only pass values that satisfy this (line 4 passes values greater than the pivot, line 5 values less than it), and a swap fixes the two values where they stopped.
Return value. When the scans cross, , and everything right of was either passed by the scan (so it is at least the pivot) or lies in the old region; everything at or left of lies at or left of and was passed by or stopped the scan, so it is at most the pivot. That gives the ordering. Finally : in the first round stops at only if pivot, and then forces a swap and another round, after which moves strictly left of .
A proof like this is easy to get subtly wrong, so the program below also checks the three claims exhaustively: every array of length 2 to 7 over the values , which includes every pattern of duplicates.
from itertools import product
def hoare_partition(a, lo, hi):
pivot = a[lo]
i, j = lo - 1, hi + 1
while True:
j -= 1
while a[j] > pivot:
j -= 1
i += 1
while a[i] < pivot:
i += 1
if i < j:
a[i], a[j] = a[j], a[i]
else:
return j
checked = 0
for m in range(2, 8):
for values in product(range(3), repeat=m):
a = list(values)
j = hoare_partition(a, 0, m - 1) # an IndexError would mean a scan ran off
assert 0 <= j < m - 1, (values, j)
assert max(a[:j + 1]) <= min(a[j + 1:]), (values, a, j)
assert sorted(a) == sorted(values)
checked += 1
print(f"{checked} arrays checked: indices in range, 0 <= j < hi, left <= right")3276 arrays checked: indices in range, 0 <= j < hi, left <= right
The trap: choosing the last element as pivot
It is tempting to make Hoare's scheme use as the pivot, like Lomuto's. That breaks the guarantee . On the array [1, 2] with pivot , the first round has (since ) and (since passes), they meet, and the procedure returns . The "left part" is the whole array, and quicksort recurses on the same input forever.
def hoare_last_pivot(a, lo, hi): # broken variant: pivot taken from the right end
pivot = a[hi]
i, j = lo - 1, hi + 1
while True:
j -= 1
while a[j] > pivot: j -= 1
i += 1
while a[i] < pivot: i += 1
if i < j: a[i], a[j] = a[j], a[i]
else: return j
def quicksort(a, lo, hi, partition, depth=0):
if lo >= hi:
return
if depth > 20:
raise RecursionError(f"no progress on a[{lo}..{hi}] = {a[lo:hi + 1]}")
j = partition(a, lo, hi)
quicksort(a, lo, j, partition, depth + 1)
quicksort(a, j + 1, hi, partition, depth + 1)
try:
quicksort([1, 2], 0, 1, hoare_last_pivot)
except RecursionError as e:
print("broken variant:", e)broken variant: no progress on a[0..1] = [1, 2]
If you need the pivot at the right end, either recurse on and instead, or swap the chosen pivot to position first. Randomized versions do the latter: pick a random index, swap it to , then partition.
Hoare versus Lomuto
Both schemes make about comparisons on elements (Hoare's scans make a couple more, because they overlap by one or two positions when they cross). The difference is in swaps and duplicates:
import random
def lomuto(a, lo, hi):
pivot, i, swaps = a[hi], lo, 0
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1; swaps += 1
a[i], a[hi] = a[hi], a[i]
return i, swaps + 1
def hoare(a, lo, hi):
pivot, i, j, swaps = a[lo], lo - 1, hi + 1, 0
while True:
j -= 1
while a[j] > pivot: j -= 1
i += 1
while a[i] < pivot: i += 1
if i < j:
a[i], a[j] = a[j], a[i]; swaps += 1
else:
return j, swaps
rng = random.Random(4)
n, trials = 1000, 200
ls = hs = 0
for _ in range(trials):
x = rng.sample(range(n), n)
ls += lomuto(list(x), 0, n - 1)[1]
hs += hoare(list(x), 0, n - 1)[1]
print(f"random permutations of {n}: Lomuto {ls / trials:.1f} swaps, Hoare {hs / trials:.1f} swaps on average")
same = [7] * 16
print("16 equal keys: Lomuto splits after", lomuto(list(same), 0, 15)[0], "| Hoare splits after", hoare(list(same), 0, 15)[0])random permutations of 1000: Lomuto 486.7 swaps, Hoare 178.2 swaps on average
16 equal keys: Lomuto splits after 0 | Hoare splits after 7
Lomuto swaps every value smaller than the pivot, about on average. Hoare swaps only pairs that are both on the wrong side, roughly on average. On equal keys, both of Hoare's scans stop at every element (the tests are strict), so they swap their way to the middle and meet there: a perfectly balanced split, where Lomuto gives the worst possible one. Stopping on equal keys looks wasteful, but it is exactly what makes the split balanced.
Test yourself
HOARE-PARTITION returns . On which subarrays does quicksort recurse?
- and
- and
- and
- only
Why do Hoare's scans stop on values **equal** to the pivot (strict < and > in the scan tests)?
- It is needed for the scans to stay in bounds and it splits runs of equal keys evenly
- It makes the partition stable
- It reduces the number of comparisons to
- There is no reason;
<=works equally well
What goes wrong if Hoare's scheme takes the pivot from instead of ?
- Nothing
- It can return , so quicksort recurses on the whole subarray again and never terminates
- It returns an index below
- It sorts in descending order