TExcelTAD
Home › Sorting & Order Statistics › Hoare Partitioning

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

text
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 j

The result is weaker than Lomuto's but enough for sorting. It returns an index jj with lo≤j<hilo \le j < hi such that

every value in a[lo..j]  ≤  every value in a[j+1..hi].\text{every value in } a[lo..j] \;\le\; \text{every value in } a[j+1..hi].

The pivot itself can end up anywhere in either part, so quicksort recurses on a[lo..j]a[lo..j] and a[j+1..hi]a[j+1..hi], both including the pivot's region, and not on "j−1j - 1" and "j+1j + 1" as with Lomuto.

python · try it yourself
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 66 is not at the boundary: it sits at the end of the right part, which is allowed, because 66 is at least everything on the left.

In C++

cpp · try it yourself
#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 a[lo..hi]a[lo..hi], the returned jj satisfies lo≤j<hilo \le j < hi (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 lolo, where the pivot itself sits, so it stops there immediately: i=loi = lo. The scan of line 4 stops at the latest at lolo too, because a[lo]≤a[lo] \le pivot. If it stops at j=loj = lo then i=ji = j and the procedure returns lolo. That is only possible when every value in a[lo+1..hi]a[lo+1..hi] is greater than the pivot, and then the split a[lo..lo]a[lo..lo], a[lo+1..hi]a[lo+1..hi] is correct.

After a swap. When i<ji < j the values swap, so now a[i]≤a[i] \le pivot and a[j]≥a[j] \ge pivot. These two values act as sentinels for the next round: the left-moving scan cannot pass position ii (it would stop there at the latest), and the right-moving scan cannot pass position jj. So neither index leaves the subarray.

Invariant. At the start of each round, every value in a[lo..i]a[lo..i] is at most the pivot and every value in a[j..hi]a[j..hi] 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, i≥ji \ge j, and everything right of jj was either passed by the jj scan (so it is at least the pivot) or lies in the old a[j..hi]a[j..hi] region; everything at or left of jj lies at or left of ii and was passed by or stopped the ii scan, so it is at most the pivot. That gives the ordering. Finally j<hij < hi: in the first round jj stops at hihi only if a[hi]≤a[hi] \le pivot, and then i=lo<hi=ji = lo < hi = j forces a swap and another round, after which jj moves strictly left of hihi.

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 {0,1,2}\{0, 1, 2\}, which includes every pattern of duplicates.

python · try it yourself
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 a[hi]a[hi] as the pivot, like Lomuto's. That breaks the guarantee j<hij < hi. On the array [1, 2] with pivot 22, the first round has j=1j = 1 (since 2≤22 \le 2) and i=1i = 1 (since 1<21 < 2 passes), they meet, and the procedure returns j=1=hij = 1 = hi. The "left part" is the whole array, and quicksort recurses on the same input forever.

python · try it yourself
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 a[lo..i−1]a[lo..i-1] and a[i..hi]a[i..hi] instead, or swap the chosen pivot to position lolo first. Randomized versions do the latter: pick a random index, swap it to lolo, then partition.

Hoare versus Lomuto

Both schemes make about mm comparisons on mm 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:

python · try it yourself
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 m/2m/2 on average. Hoare swaps only pairs that are both on the wrong side, roughly m/6m/6 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 jj. On which subarrays does quicksort recurse?

  1. a[lo..j−1]a[lo..j-1] and a[j+1..hi]a[j+1..hi]
  2. a[lo..j]a[lo..j] and a[j+1..hi]a[j+1..hi]
  3. a[lo..j]a[lo..j] and a[j..hi]a[j..hi]
  4. only a[lo..j]a[lo..j]

Why do Hoare's scans stop on values **equal** to the pivot (strict < and > in the scan tests)?

  1. It is needed for the scans to stay in bounds and it splits runs of equal keys evenly
  2. It makes the partition stable
  3. It reduces the number of comparisons to m/2m/2
  4. There is no reason; <= works equally well

What goes wrong if Hoare's scheme takes the pivot from a[hi]a[hi] instead of a[lo]a[lo]?

  1. Nothing
  2. It can return j=hij = hi, so quicksort recurses on the whole subarray again and never terminates
  3. It returns an index below lolo
  4. It sorts in descending order