TExcelTAD
Home › Sorting & Order Statistics › Duplicate Keys and Three-Way Partitioning

Duplicate Keys and Three-Way Partitioning

Real data is full of repeated keys: sorting orders by country, people by age, log lines by severity. Two-way partitioning handles them badly or at best indifferently. Lomuto's scheme sends every key equal to the pivot to the same side, so an array of equal keys costs Θ(n2)\Theta(n^2). Hoare's scheme splits equal keys evenly, which is Θ(nlg⁡n)\Theta(n \lg n), but that is still wasted work: once you know a block of keys are all equal to the pivot, they are sorted already. Three-way partitioning splits the subarray into three parts, smaller than, equal to and larger than the pivot, and never touches the middle part again.

The Dutch national flag

Edsger Dijkstra posed the problem as sorting a row of red, white and blue pebbles in one pass, with only swaps, like the three bands of the Dutch flag. With the pivot as "white", that is exactly three-way partitioning. The scheme keeps four regions with three indices:

text
 lo          lt            i              gt          hi
 +-----------+-------------+--------------+------------+
 |  < pivot  |  = pivot    |  not yet seen |  > pivot   |
 +-----------+-------------+--------------+------------+
text
THREE-WAY-PARTITION(a, lo, hi)    // returns (lt, gt): a[lt..gt] are the keys equal to the pivot
1  pivot = a[lo]
2  lt = lo,  i = lo,  gt = hi
3  while i <= gt
4      if a[i] < pivot
5          swap a[lt] and a[i];  lt = lt + 1;  i = i + 1
6      else if a[i] > pivot
7          swap a[i] and a[gt];  gt = gt - 1          // i stays: the value from gt is unseen
8      else
9          i = i + 1
10 return (lt, gt)

Invariant. At the start of each iteration: a[lo:lt]a[lo:lt] is less than the pivot, a[lt:i]a[lt:i] equals the pivot, and a[gt+1..hi]a[gt+1..hi] is greater than the pivot.

  • Initialization. lt=i=lolt = i = lo and gt=higt = hi, so all three regions are empty. (The pivot value itself is still unseen at position lolo; it will be the first value classified as "equal".)
  • Maintenance. A small value at ii swaps with the first equal value at ltlt (or with itself, if the equal region is empty), and both boundaries move right. A large value swaps with the last unseen value at gtgt, and only gtgt moves; ii stays, because the value that arrived from gtgt has not been examined. An equal value just extends the middle region.
  • Termination. Each iteration either increases ii or decreases gtgt, so the unseen region a[i..gt]a[i..gt] shrinks by one every time, and the loop ends when it is empty. Then the three regions cover the subarray, which is the required result.

The trace below partitions an array of the values 0, 1 and 2 around the pivot 11, which sorts it completely: this is the practice problem Sort Colors.

python · try it yourself
def three_way_partition(a, lo, hi, trace=False):
    pivot = a[lo]
    lt, i, gt = lo, lo, hi
    while i <= gt:
        if a[i] < pivot:
            a[lt], a[i] = a[i], a[lt]
            lt += 1; i += 1
            step = "less: swap to the front"
        elif a[i] > pivot:
            a[i], a[gt] = a[gt], a[i]
            gt -= 1
            step = "greater: swap to the back"
        else:
            i += 1
            step = "equal: keep"
        if trace:
            print(f"  {step:26} {a}  lt={lt} i={i} gt={gt}")
    return lt, gt

a = [1, 2, 0, 2, 1, 0, 1, 2, 0]
print("pivot", a[0], "in", a)
lt, gt = three_way_partition(a, 0, len(a) - 1, trace=True)
print(f"less {a[:lt]}, equal {a[lt:gt + 1]}, greater {a[gt + 1:]}")
pivot 1 in [1, 2, 0, 2, 1, 0, 1, 2, 0]
  equal: keep                [1, 2, 0, 2, 1, 0, 1, 2, 0]  lt=0 i=1 gt=8
  greater: swap to the back  [1, 0, 0, 2, 1, 0, 1, 2, 2]  lt=0 i=1 gt=7
  less: swap to the front    [0, 1, 0, 2, 1, 0, 1, 2, 2]  lt=1 i=2 gt=7
  less: swap to the front    [0, 0, 1, 2, 1, 0, 1, 2, 2]  lt=2 i=3 gt=7
  greater: swap to the back  [0, 0, 1, 2, 1, 0, 1, 2, 2]  lt=2 i=3 gt=6
  greater: swap to the back  [0, 0, 1, 1, 1, 0, 2, 2, 2]  lt=2 i=3 gt=5
  equal: keep                [0, 0, 1, 1, 1, 0, 2, 2, 2]  lt=2 i=4 gt=5
  equal: keep                [0, 0, 1, 1, 1, 0, 2, 2, 2]  lt=2 i=5 gt=5
  less: swap to the front    [0, 0, 0, 1, 1, 1, 2, 2, 2]  lt=3 i=6 gt=5
less [0, 0, 0], equal [1, 1, 1], greater [2, 2, 2]

Every value was examined exactly once, with at most two comparisons (less? greater?) and at most one swap each.

In C++

cpp · try it yourself
#include <cstdio>
#include <utility>
#include <vector>

// Partitions a[lo..hi] around a[lo]; afterwards a[lt..gt] holds the keys equal to the pivot.
std::pair<int, int> three_way_partition(std::vector<int>& a, int lo, int hi) {
    int pivot = a[lo], lt = lo, i = lo, gt = hi;
    while (i <= gt) {
        if (a[i] < pivot) std::swap(a[lt++], a[i++]);
        else if (a[i] > pivot) std::swap(a[i], a[gt--]);
        else ++i;
    }
    return {lt, gt};
}

void quicksort3(std::vector<int>& a, int lo, int hi) {
    if (lo >= hi) return;
    auto [lt, gt] = three_way_partition(a, lo, hi);
    quicksort3(a, lo, lt - 1);    // the equal block a[lt..gt] is finished
    quicksort3(a, gt + 1, hi);
}

int main() {
    std::vector<int> a = {1, 2, 0, 2, 1, 0, 1, 2, 0};
    auto [lt, gt] = three_way_partition(a, 0, static_cast<int>(a.size()) - 1);
    std::printf("equal block a[%d..%d]:", lt, gt);
    for (int x : a) std::printf(" %d", x);
    std::printf("\n");
    std::vector<int> b = {5, 3, 5, 9, 5, 1, 3, 5, 9, 5, 0, 5};
    quicksort3(b, 0, static_cast<int>(b.size()) - 1);
    std::printf("sorted:");
    for (int x : b) std::printf(" %d", x);
    std::printf("\n");
}
equal block a[3..5]: 0 0 0 1 1 1 2 2 2
sorted: 0 1 3 3 5 5 5 5 5 5 9 9

Three-way quicksort

text
QUICKSORT-3WAY(a, lo, hi)
1  if lo < hi
2      swap a[lo] with a uniformly random element of a[lo..hi]
3      (lt, gt) = THREE-WAY-PARTITION(a, lo, hi)
4      QUICKSORT-3WAY(a, lo, lt - 1)
5      QUICKSORT-3WAY(a, gt + 1, hi)

Correctness is the same induction as for ordinary quicksort, with the equal block playing the role of the single pivot. The difference is in the cost: each recursive call removes a whole class of equal keys, not just one element. Keys with equal values always stay together in one subarray (partitions split by value), and every partition removes the whole class of its pivot, so with kk distinct values there are at most kk partitions in total. With all keys equal the whole sort is one linear pass. More generally, with kk distinct values the expected cost is O(nlg⁡k)O(n \lg k), and it is within a constant factor of the best possible for the given multiset of keys (the entropy bound, a refinement of the decision-tree lower bound that takes the duplicates into account).

Measuring the difference

Three randomized quicksorts on n=2000n = 2000 keys with kk distinct values each, counting key comparisons. For the three-way version, "less?" and "greater?" count as two comparisons when both are needed.

python · try it yourself
import random

def lomuto_qs(a, rng):
    c, st = 0, [(0, len(a) - 1)]
    while st:
        lo, hi = st.pop()
        if lo >= hi: continue
        r = rng.randint(lo, hi); a[r], a[hi] = a[hi], a[r]
        p, i = a[hi], lo
        for j in range(lo, hi):
            c += 1
            if a[j] < p: a[i], a[j] = a[j], a[i]; i += 1
        a[i], a[hi] = a[hi], a[i]
        st += [(lo, i - 1), (i + 1, hi)]
    return c

def hoare_qs(a, rng):
    c, st = 0, [(0, len(a) - 1)]
    while st:
        lo, hi = st.pop()
        if lo >= hi: continue
        r = rng.randint(lo, hi); a[r], a[lo] = a[lo], a[r]
        p, i, j = a[lo], lo - 1, hi + 1
        while True:
            j -= 1; c += 1
            while a[j] > p: j -= 1; c += 1
            i += 1; c += 1
            while a[i] < p: i += 1; c += 1
            if i >= j: break
            a[i], a[j] = a[j], a[i]
        st += [(lo, j), (j + 1, hi)]
    return c

def three_way_qs(a, rng):
    c, st = 0, [(0, len(a) - 1)]
    while st:
        lo, hi = st.pop()
        if lo >= hi: continue
        r = rng.randint(lo, hi); a[r], a[lo] = a[lo], a[r]
        p, lt, i, gt = a[lo], lo, lo, hi
        while i <= gt:
            c += 1
            if a[i] < p: a[lt], a[i] = a[i], a[lt]; lt += 1; i += 1
            else:
                c += 1
                if a[i] > p: a[i], a[gt] = a[gt], a[i]; gt -= 1
                else: i += 1
        st += [(lo, lt - 1), (gt + 1, hi)]
    return c

n = 2000
rng = random.Random(6)
print(f"{'distinct keys':>13} {'Lomuto':>9} {'Hoare':>8} {'3-way':>8}")
for k in [1, 2, 10, 100, 2000]:
    data = [rng.randrange(k) for _ in range(n)] if k < n else rng.sample(range(n), n)
    results = []
    for sort in (lomuto_qs, hoare_qs, three_way_qs):
        a = list(data)
        results.append(sort(a, rng))
        assert a == sorted(data)
    print(f"{k:>13} {results[0]:>9} {results[1]:>8} {results[2]:>8}")
distinct keys    Lomuto    Hoare    3-way
            1   1999000    25726     4000
            2   1006840    25946     4939
           10    209883    26741    11695
          100     36177    32662    25908
         2000     23719    32078    39562

The table tells the story of the last three lessons in one picture:

  • With one distinct key, Lomuto is quadratic (n(n−1)2=1,999,000\frac{n(n-1)}{2} = 1{,}999{,}000), Hoare is nlg⁡nn \lg n-ish, and three-way partitioning finishes in a single pass of about 2n2n comparisons.
  • With few distinct keys, three-way is far ahead, and Lomuto is still quadratic within each class of equal keys.
  • With all keys distinct, three-way partitioning pays for its second comparison and is the most expensive of the three. That is why library sorts use it adaptively, switching it on only when they notice many equal keys (Quicksort in Practice).
  • Hoare's column is above Lomuto's on distinct keys. This simple version of Hoare's scheme leaves the pivot inside one of the two parts, so the recursion handles a few more elements, and its scans overlap by a position or two at every partition. Its advantage is in swaps, not comparisons.

Note: The two-comparison cost can be reduced. Bentley and McIlroy's variant of three-way partitioning swaps equal keys to the two ends during a Hoare-style scan and moves them to the middle at the end, so distinct keys cost one comparison each, as in Hoare's scheme.

Test yourself

In THREE-WAY-PARTITION, why does ii **not** advance after swapping a large value with a[gt]a[gt]?

  1. To save a comparison
  2. Because the value that arrived at position ii from gtgt has not been examined yet
  3. Because ii must stay equal to ltlt
  4. It does advance; the pseudocode is wrong

How many comparisons does three-way quicksort need on nn equal keys?

  1. about n(n−1)/2n(n-1)/2
  2. about nlg⁡nn \lg n
  3. about nn (a single pass)
  4. 0

On an array of nn **distinct** keys, which statement is true?

  1. Three-way partitioning makes it linear
  2. Three-way partitioning gives no benefit, and the simple version costs up to two comparisons per element
  3. Lomuto partitioning becomes quadratic
  4. Hoare partitioning fails