Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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

python
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: jj reads, ii marks the end of the small region.

DerivationProof: a loop invariant with three regions
  1. a[lo..i]≤p,a[i+1..j−1]>p,a[hi]=pa[\mathit{lo}..i]\le p,\qquad a[i+1..j-1]>p,\qquad a[\mathit{hi}]=p

    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:

  2. a[j]≤p:a[lo..i]⏟≤p a[i+1..j]⏟>p  after i←i+1, a[i]↔a[j]a[j]\le p:\quad \underbrace{a[\mathit{lo}..i]}_{\le p}\ \underbrace{a[i+1..j]}_{>p}\ \text{ after } i\leftarrow i+1,\ a[i]\leftrightarrow a[j]

    Initialization. i=lo−1i=\mathit{lo}-1 and j=loj=\mathit{lo}: both regions are empty. Maintenance. If a[j]>pa[j]>p, incrementing jj extends the large region. If a[j]≤pa[j]\le p, then ii advances and a[i]a[i], the first element of the large region (or a[j]a[j] itself if that region is empty), trades places with a[j]a[j]: the small region grows by one and the large region shifts one place right.

  3. a[lo..q−1]≤p=a[q]<a[q+1..hi]a[\mathit{lo}..q-1]\le p=a[q]<a[q+1..\mathit{hi}]

    Termination. When j=hij=\mathit{hi}, every element but the pivot is classified. Swapping the pivot with a[i+1]a[i+1], the first large element, puts it between the regions, which is the postcondition with q=i+1q=i+1:

Exact cost. A part of nn elements costs exactly n−1n-1 comparisons. It makes one swap per element ≤p\le p plus the final one; on a random permutation the pivot's rank is uniform, so that is (n+1)/2(n+1)/2 swaps on average, many of them swaps of a cell with itself.

Duplicates are its weak spot. Every key equal to pp joins the small side. On an array of nn equal keys the split is (n−1,0)(n-1,0) at every level, and quicksort makes n(n−1)/2n(n-1)/2 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 pp, the right one skips elements larger than pp, and when both stop, the two misplaced elements trade places. Both scans stop on keys equal to pp, which looks wasteful and is the whole point.

python
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)
DerivationProof
  1. i1=lo,lo≤j1≤hii_1=\mathit{lo},\qquad \mathit{lo}\le j_1\le\mathit{hi}

    First round. ii stops at once at lo\mathit{lo}, because a[lo]=pa[\mathit{lo}]=p is not <p<p. The jj-scan stops at lo\mathit{lo} at the latest, because a[lo]=pa[\mathit{lo}]=p is not >p>p. If j=loj=\mathit{lo} the call returns lo<hi\mathit{lo}<\mathit{hi}.

  2. a[lo..i]≤p≤a[j..hi]a[\mathit{lo}..i]\le p\le a[j..\mathit{hi}]

    Sentinels. After each swap, the cell at ii holds a value ≤p\le p and the cell at jj a value ≥p\ge p, and everything left of ii is ≤p\le p, everything right of jj is ≥p\ge p. So in the next round the ii-scan stops at the old jj at the latest and the jj-scan at the old ii at the latest: no index check is needed.

  3. a[lo..j] ≤ p ≤ a[j+1..hi],lo≤j<hia[\mathit{lo}..j]\ \le\ p\ \le\ a[j+1..\mathit{hi}],\qquad \mathit{lo}\le j<\mathit{hi}

    Return. When i≥ji\ge j, the scans have classified everything: a[lo..i−1]≤pa[\mathit{lo}..i-1]\le p and a[j+1..hi]≥pa[j+1..\mathit{hi}]\ge p, and a[j]≤pa[j]\le p when i=ji=j. A swap in the first round moves jj below hi\mathit{hi} in every later round, so j<hij<\mathit{hi}.

Per partition of nn keysLomutoHoare
Comparisonsexactly n−1n-1n+O(1)n+O(1), usually n+2n+2 because the scans cross
Swaps, random permutation(n+1)/2(n+1)/2 on averageabout n/6n/6 on average
nn equal keyssplit (n−1,0)(n-1,0)split in the middle
Pivot ends in its final place?yes, at qqnot necessarily
Measured on random permutations (Hoare: 168 swaps on average for n=1000n=1000; Lomuto: 495), and exact for the other rows. Over a whole quicksort, Hoare's scheme makes about 13nln⁡n\tfrac13 n\ln n swaps against roughly nln⁡nn\ln n for Lomuto's.
Check your understanding

Quicksort partitions an array of nn equal keys. What split does each scheme produce at the top level?

  1. Both split it in the middle
  2. Both split it (n−1,0)(n-1,0)
  3. Lomuto splits it in the middle; Hoare splits it (n−1,0)(n-1,0)
  4. Lomuto splits it (n−1,0)(n-1,0); Hoare splits it in the middle
Show the answer

D. Lomuto splits it (n−1,0)(n-1,0); Hoare splits it in the middle

Lomuto sends every key ≤p\le p left, so all of them go left. Hoare's scans stop at every key equal to pp, 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 Θ(nlog⁡n)\Theta(n\log n) 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 pp", "equal to pp" and "greater than pp", and the Dutch national flag partition puts every key equal to the pivot in its final place at once.

python
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]
DerivationThe four-region invariant
  1. a[lo..lt−1]⏟< p  a[lt..i−1]⏟= p  a[i..gt]⏟unknown  a[gt+1..hi]⏟> p\underbrace{a[\mathit{lo}..\mathit{lt}-1]}_{<\,p}\ \ \underbrace{a[\mathit{lt}..i-1]}_{=\,p}\ \ \underbrace{a[i..\mathit{gt}]}_{\text{unknown}}\ \ \underbrace{a[\mathit{gt}+1..\mathit{hi}]}_{>\,p}

    At the top of each iteration the array is split into four regions, one of them still unknown:

  2. each case keeps all four region properties\text{each case keeps all four region properties}

    a[i]<pa[i]<p: swap it with a[lt]a[\mathit{lt}], the first equal key (or a[i]a[i] itself if no equal key has been seen), then advance both. a[i]=pa[i]=p: advance ii. a[i]>pa[i]>p: swap it with a[gt]a[\mathit{gt}], the last unknown key, and shrink the large region's boundary; the key that arrives at ii is unknown, so ii stays.

  3. (gt−i+1) falls by 1 per iteration:n iterations(\mathit{gt}-i+1)\ \text{falls by 1 per iteration:}\quad n\ \text{iterations}

    Cost. Every iteration shrinks the unknown region by exactly one, so a part of nn keys takes exactly nn iterations, at most nn swaps and at most 2n2n comparisons. When the unknown region is empty, the invariant is the postcondition.

Check your understanding

In the three-way loop, after swapping a[i]a[i] with a[gt]a[\mathit{gt}], why must ii not advance?

  1. Advancing would make the loop run past hi\mathit{hi}
  2. The key that just arrived at position ii came from the unknown region and has not been compared with pp
  3. The key sent to gt\mathit{gt} might be equal to pp
  4. Advancing ii would make the partition unstable
Show the answer

B. The key that just arrived at position ii came from the unknown region and has not been compared with pp

After the swap, a[i]a[i] holds what was a[gt]a[\mathit{gt}], an unexamined key that may be smaller than, equal to or larger than pp. The next iteration classifies it. By contrast, a swap with a[lt]a[\mathit{lt}] brings back a key already known to equal pp (or a[i]a[i] itself), so there ii may advance.

Three-way quicksort recurses only on the <p<p and >p>p parts. Each partition removes the pivot's value from both subproblems, so with dd distinct keys the recursion is at most dd levels deep, and the total work is O(n⋅d)O(n\cdot d) for any pivot rule. On nn equal keys that is a single pass, Θ(n)\Theta(n), where Lomuto's scheme needs n(n−1)/2n(n-1)/2 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 pp 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 O(n)O(n) 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 a[lo:hi]a[\mathit{lo}:\mathit{hi}] here:

python
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)
DerivationCorrect, in place, and Θ(n log n)
  1. P1 F1 P2 F2 ⟶ P1 P2 F1 F2P_1\,F_1\,P_2\,F_2\ \longrightarrow\ P_1\,P_2\,F_1\,F_2

    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:

  2. (F1R P2R)R=P2 F1\big(F_1^{R}\,P_2^{R}\big)^{R}=P_2\,F_1

    Three reversals exchange two adjacent blocks, since reversing a concatenation reverses the order of the pieces:

  3. T(n)=2 T(n/2)+O(n)=O(nlog⁡n),O(log⁡n) stackT(n)=2\,T(n/2)+O(n)=O(n\log n),\qquad O(\log n)\ \text{stack}

    The reversals cost at most nn swaps on a range of nn elements, and the recursion halves the range:

C++'s std::stable_partition makes this trade explicitly: O(n)O(n) swaps when it can allocate a buffer, at most nlog⁡2nn\log_2 n swaps when it cannot. Linear-time stable partitioning with O(1)O(1) 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:

text
// 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 a[lo..i]≤p<a[i+1..j−1]a[\mathit{lo}..i]\le p<a[i+1..j-1]: exactly n−1n-1 comparisons and about n/2n/2 swaps, the pivot placed exactly, but all-equal keys split (n−1,0)(n-1,0) 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 n/6n/6 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: nn iterations, at most nn swaps; three-way quicksort is O(nd)O(nd) for dd 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.

Question 1

Lomuto's partition runs on [3,8,2,5,1,4][3,8,2,5,1,4] with the last element, 4, as pivot. What does it return, and what does the array hold afterward?

  1. 3, with [3,2,1,4,8,5][3,2,1,4,8,5]
  2. 3, with [1,2,3,4,5,8][1,2,3,4,5,8]
  3. 3, with [2,1,3,4,8,5][2,1,3,4,8,5]
  4. 2, with [3,2,1,4,8,5][3,2,1,4,8,5]
Show the answer

A. 3, with [3,2,1,4,8,5][3,2,1,4,8,5]

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: [3,2,1,4‾,8,5][3,2,1,\underline{4},8,5], q=3q=3. Partitioning separates small from large; it sorts neither side.

Question 2

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?

  1. Python raises an exception, which the caller catches
  2. After every swap, a value ≥p\ge p sits at jj and a value ≤p\le p at ii, so each scan stops at the other's position at the latest
  3. The pivot is copied to both ends of the array before the loop
  4. The scans stop after n/2n/2 steps
Show the answer

B. After every swap, a value ≥p\ge p sits at jj and a value ≤p\le p at ii, so each scan stops at the other's position at the latest

In the first round the pivot itself at lo\mathit{lo} stops both scans; afterward the two swapped values act as sentinels. Changing < to <= breaks exactly this argument.

Question 3

Quicksort with three-way partitioning sorts an array of nn equal keys. How much work does it do?

  1. Θ(nlog⁡n)\Theta(n\log n): the recursion still halves the array
  2. Θ(n2)\Theta(n^2): every key joins the same side
  3. It depends on the pivot rule
  4. Θ(n)\Theta(n): one partition pass puts every key in the equal block, and both recursive calls are empty
Show the answer

D. Θ(n)\Theta(n): 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 lt=lo\mathit{lt}=\mathit{lo} and gt=hi\mathit{gt}=\mathit{hi} after nn iterations, and nothing is left to sort. In general, dd distinct keys mean at most dd levels of recursion, O(nd)O(nd) in all.

Question 4

You stably partition nn records in place with the divide-and-conquer method (recursive halves, then a rotation by three reversals). What does it cost?

  1. Θ(n)\Theta(n) time, like an unstable partition
  2. Θ(nlog⁡n)\Theta(n\log n) time and O(log⁡n)O(\log n) stack
  3. Θ(n2)\Theta(n^2) time, because every rotation moves the whole array
  4. Θ(nlog⁡2n)\Theta(n\log^2 n) time
Show the answer

B. Θ(nlog⁡n)\Theta(n\log n) time and O(log⁡n)O(\log n) stack

Each level of recursion rotates disjoint ranges with at most nn swaps in total, and there are ⌈log⁡2n⌉\lceil\log_2 n\rceil levels: T(n)=2T(n/2)+O(n)T(n)=2T(n/2)+O(n). 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.