In-Place Partitioning
Dutch national flag, Lomuto and Hoare, and the invariants that make them correct.
Quicksort's speed lives in a loop of about ten lines. Partitioning around a pivot looks trivial, yet the two classic schemes behave very differently: on an array of equal keys, Lomuto's sends quicksort to quadratic time while Hoare's splits it exactly in half. Getting such loops right is an exercise in invariants, and getting them fast is still an engineering frontier.
What you’ll learn
- State and prove the invariants of Lomuto's and Hoare's partition schemes, including termination and the absence of out-of-bounds accesses.
- Compare the schemes' comparisons and swaps, exactly and on random input, and their behavior on duplicate keys.
- Solve the Dutch national flag problem in one pass with a four-region invariant, and use three-way partitioning in quicksort.
- Explain why stable in-place partitioning costs an extra logarithmic factor in practice, and how block partitioning avoids branch mispredictions.
Lomuto's scheme and its invariant
def lomuto(a, lo, hi):
"""Partition a[lo..hi] around p = a[hi]; return q with a[lo..q-1] <= p = a[q] < a[q+1..hi]."""
p = a[hi]
i = lo - 1 # a[lo..i] <= p
for j in range(lo, hi): # a[i+1..j-1] > p
if a[j] <= p:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
return i + 1
a = [3, 8, 2, 5, 1, 4]
print(lomuto(a, 0, 5), a) # 3 [3, 2, 1, 4, 8, 5]The Lomuto partition, popularized by Bentley's Programming Pearls (which credits Nico Lomuto) and used in CLRS. Two same-direction pointers: reads, marks the end of the small region.
Invariant. At the top of each iteration, the scanned part splits into a small region and a large region, and the pivot waits at the end:
Initialization. and : both regions are empty. Maintenance. If , incrementing extends the large region. If , then advances and , the first element of the large region (or itself if that region is empty), trades places with : the small region grows by one and the large region shifts one place right.
Termination. When , every element but the pivot is classified. Swapping the pivot with , the first large element, puts it between the regions, which is the postcondition with :
Exact cost. A part of elements costs exactly comparisons. It makes one swap per element plus the final one; on a random permutation the pivot's rank is uniform, so that is swaps on average, many of them swaps of a cell with itself.
Duplicates are its weak spot. Every key equal to joins the small side. On an array of equal keys the split is at every level, and quicksort makes comparisons, exactly as on sorted input with the last element as pivot.
Hoare's scheme: two pointers from both ends
Hoare's original partition (1961) runs two pointers toward each other. The left one skips elements smaller than , the right one skips elements larger than , and when both stop, the two misplaced elements trade places. Both scans stop on keys equal to , which looks wasteful and is the whole point.
def hoare(a, lo, hi):
"""Partition a[lo..hi], lo < hi, around p = a[lo]. Return j with lo <= j < hi
and every element of a[lo..j] <= p <= every element of a[j+1..hi]."""
p = a[lo]
i, j = lo - 1, hi + 1
while True:
i += 1
while a[i] < p: # stop at an element >= p
i += 1
j -= 1
while a[j] > p: # stop at an element <= p
j -= 1
if i >= j:
return j
a[i], a[j] = a[j], a[i]
def quicksort(a, lo, hi):
if lo < hi:
j = hoare(a, lo, hi)
quicksort(a, lo, j) # the pivot need not be at j
quicksort(a, j + 1, hi)First round. stops at once at , because is not . The -scan stops at at the latest, because is not . If the call returns .
Sentinels. After each swap, the cell at holds a value and the cell at a value , and everything left of is , everything right of is . So in the next round the -scan stops at the old at the latest and the -scan at the old at the latest: no index check is needed.
Return. When , the scans have classified everything: and , and when . A swap in the first round moves below in every later round, so .
| Per partition of keys | Lomuto | Hoare |
|---|---|---|
| Comparisons | exactly | , usually because the scans cross |
| Swaps, random permutation | on average | about on average |
| equal keys | split | split in the middle |
| Pivot ends in its final place? | yes, at | not necessarily |
Quicksort partitions an array of equal keys. What split does each scheme produce at the top level?
- Both split it in the middle
- Both split it
- Lomuto splits it in the middle; Hoare splits it
- Lomuto splits it ; Hoare splits it in the middle
Show the answer
D. Lomuto splits it ; Hoare splits it in the middle
Lomuto sends every key left, so all of them go left. Hoare's scans stop at every key equal to , so each round swaps one pair and moves both pointers one step; they meet in the middle. Hence quadratic time for Lomuto on all-equal input and for Hoare.
Three-way partitioning: the Dutch national flag
Dijkstra posed the problem in A Discipline of Programming (1976): a row of pebbles, each red, white or blue, must be rearranged into the order of the Dutch flag using swaps, inspecting each pebble once. For sorting, the colors are "less than ", "equal to " and "greater than ", and the Dutch national flag partition puts every key equal to the pivot in its final place at once.
def three_way(a, lo, hi, p):
"""Rearrange a[lo..hi] into keys < p, == p, > p. Return (lt, gt) with
a[lo..lt-1] < p, a[lt..gt] == p, a[gt+1..hi] > p."""
lt, i, gt = lo, lo, hi
while i <= gt: # a[i..gt] is still unknown
if a[i] < p:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > p:
a[i], a[gt] = a[gt], a[i]
gt -= 1 # a[i] is now an unexamined key
else:
i += 1
return lt, gt
a = [2, 0, 2, 1, 1, 0]
print(three_way(a, 0, 5, 1), a) # (2, 3) [0, 0, 1, 1, 2, 2]At the top of each iteration the array is split into four regions, one of them still unknown:
: swap it with , the first equal key (or itself if no equal key has been seen), then advance both. : advance . : swap it with , the last unknown key, and shrink the large region's boundary; the key that arrives at is unknown, so stays.
Cost. Every iteration shrinks the unknown region by exactly one, so a part of keys takes exactly iterations, at most swaps and at most comparisons. When the unknown region is empty, the invariant is the postcondition.
In the three-way loop, after swapping with , why must not advance?
- Advancing would make the loop run past
- The key that just arrived at position came from the unknown region and has not been compared with
- The key sent to might be equal to
- Advancing would make the partition unstable
Show the answer
B. The key that just arrived at position came from the unknown region and has not been compared with
After the swap, holds what was , an unexamined key that may be smaller than, equal to or larger than . The next iteration classifies it. By contrast, a swap with brings back a key already known to equal (or itself), so there may advance.
Three-way quicksort recurses only on the and parts. Each partition removes the pivot's value from both subproblems, so with distinct keys the recursion is at most levels deep, and the total work is for any pivot rule. On equal keys that is a single pass, , where Lomuto's scheme needs comparisons.
Dijkstra's loop swaps even when there are few equal keys. Bentley and McIlroy's "Engineering a sort function" (1993) instead runs a Hoare-style scan that parks keys equal to at both ends, then swaps the two parked blocks into the middle at the end; it pays for equal keys only when they exist.
Stability, branches and the engineering frontier
None of these schemes is stable: swaps across the array reorder equal keys, as the widget showed. A stable partition keeps the original order inside each side. With an buffer it is one pass: copy the passing elements, then the failing ones. In place, the simple method is divide and conquer, with half-open ranges here:
def reverse(a, i, j): # reverse the half-open block a[i:j]
j -= 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
def stable_partition(a, lo, hi, pred):
"""Stably move the elements of a[lo:hi] that satisfy pred to the front, in place.
Returns the index of the first element that fails pred."""
if hi - lo <= 1:
return hi if hi > lo and pred(a[lo]) else lo
mid = (lo + hi) // 2
m1 = stable_partition(a, lo, mid, pred) # a[lo:m1] pass, a[m1:mid] fail
m2 = stable_partition(a, mid, hi, pred) # a[mid:m2] pass, a[m2:hi] fail
reverse(a, m1, mid) # rotate a[m1:m2] so that the
reverse(a, mid, m2) # passing block a[mid:m2] comes
reverse(a, m1, m2) # before the failing block a[m1:mid]
return m1 + (m2 - mid)By induction, the two recursive calls leave four blocks, each in its original order: passing and failing elements of the left half, then of the right half. Exchanging the two middle blocks finishes the job without reordering inside any block:
Three reversals exchange two adjacent blocks, since reversing a concatenation reverses the order of the pieces:
The reversals cost at most swaps on a range of elements, and the recursion halves the range:
C++'s std::stable_partition makes this trade explicitly: swaps when it can allocate a buffer, at most swaps when it cannot. Linear-time stable partitioning with extra words is possible in theory, but the known methods are intricate and slow in practice.
On real hardware the cost that matters is often not comparisons but branch mispredictions. A processor guesses which way if a[j] <= p will go long before it knows; with a pivot near the median, every comparison is a coin flip, about half the guesses are wrong, and each wrong guess discards many cycles of work in flight. Block partitioning (BlockQuicksort; Edelkamp & Weiß, 2016) separates comparing from moving:
// left block a[l .. l+B-1]: record where the elements that belong on the right sit
numL ← 0
for t ← 0 to B − 1:
offsetsL[numL] ← t
numL ← numL + [a[l + t] ≥ p] // the comparison is used as 0 or 1
// right block a[r-B+1 .. r]: record where the elements that belong on the left sit
numR ← 0
for t ← 0 to B − 1:
offsetsR[numR] ← t
numR ← numR + [a[r − t] < p]
// swap misplaced pairs; refill whichever buffer runs empty with the next block
for k ← 0 to min(numL, numR) − 1:
swap a[l + offsetsL[k]] and a[r − offsetsR[k]]The comparison outcome becomes a number added to a counter, so the scanning loops contain no branch that depends on the data. Pattern-defeating quicksort (Peters, 2021) uses the same technique for keys that are cheap to compare.
Key takeaways
- Lomuto's partition keeps : exactly comparisons and about swaps, the pivot placed exactly, but all-equal keys split and make quicksort quadratic.
- Hoare's partition scans from both ends and stops on equal keys: sentinels make it safe without index checks, it swaps about times on random input, and it splits equal keys evenly, though the pivot may not end in its final place.
- Dijkstra's Dutch national flag partition keeps four regions and settles one key per iteration: iterations, at most swaps; three-way quicksort is for distinct keys, linear when all keys are equal.
- Stability in place costs a logarithmic factor with the simple method; on modern processors branch mispredictions, not comparisons, dominate, which is why block partitioning turns comparisons into arithmetic.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Lomuto's partition runs on with the last element, 4, as pivot. What does it return, and what does the array hold afterward?
- 3, with
- 3, with
- 3, with
- 2, with
Show the answer
A. 3, with
3 stays put (a swap with itself), 2 swaps with 8, 1 swaps with the 8 that moved, and finally the pivot swaps with the first large element: , . Partitioning separates small from large; it sorts neither side.
Hoare's inner loops while a[i] < p and while a[j] > p have no index checks. Why can they not run off the array?
- Python raises an exception, which the caller catches
- After every swap, a value sits at and a value at , so each scan stops at the other's position at the latest
- The pivot is copied to both ends of the array before the loop
- The scans stop after steps
Show the answer
B. After every swap, a value sits at and a value at , so each scan stops at the other's position at the latest
In the first round the pivot itself at stops both scans; afterward the two swapped values act as sentinels. Changing < to <= breaks exactly this argument.
Quicksort with three-way partitioning sorts an array of equal keys. How much work does it do?
- : the recursion still halves the array
- : every key joins the same side
- It depends on the pivot rule
- : one partition pass puts every key in the equal block, and both recursive calls are empty
Show the answer
D. : one partition pass puts every key in the equal block, and both recursive calls are empty
All keys equal the pivot, so the first pass ends with and after iterations, and nothing is left to sort. In general, distinct keys mean at most levels of recursion, in all.
You stably partition records in place with the divide-and-conquer method (recursive halves, then a rotation by three reversals). What does it cost?
- time, like an unstable partition
- time and stack
- time, because every rotation moves the whole array
- time
Show the answer
B. time and stack
Each level of recursion rotates disjoint ranges with at most swaps in total, and there are levels: . The stack holds one frame per level.
Further reading
- C. A. R. Hoare, "Quicksort," The Computer Journal 5(1) (1962), 10–15.
- E. W. Dijkstra, A Discipline of Programming (Prentice-Hall, 1976): the Dutch national flag problem.
- J. L. Bentley & M. D. McIlroy, "Engineering a sort function," Software: Practice and Experience 23(11) (1993), 1249–1265.
- S. Edelkamp & A. Weiß, "BlockQuicksort: Avoiding branch mispredictions in Quicksort," European Symposium on Algorithms (ESA) 2016.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 7 and its problems on Hoare's partition.