Sub topic 12
Three-Way Partitioning for Duplicate Keys
Earlier chapters treated the pivot as one value that ends up in one slot. That assumption causes trouble when the input contains many copies of the same key. This chapter shows why two-way partitioning slows down on duplicates and how a three-way partition fixes it. It also covers what the fix costs.
This chapter assumes you have read the chapters on the Lomuto scheme, the complexity analysis, and randomized pivots. You should be comfortable reading a loop invariant, which is a statement about the array that stays true at the start of every loop iteration.
Why duplicates hurt two-way partitioning
Real data often contains repeated values. Some examples are status codes, ages, country names, and boolean flags. If you sort a million records by a field with five possible values, almost every comparison is between equal keys.
Take the Lomuto partition with the test a[j] < pivot. On an array where every element is equal, no element is less than the pivot. The index i never moves, the pivot is swapped to position lo, and the partition returns lo. The left side is empty and the right side holds n - 1 elements. Every level of recursion removes one element, so the work is (n-1) + (n-2) + ... + 1, which is O(n²). The recursion depth is also n, which in Python soon hits the default recursion limit.
A random pivot does not help here. Every candidate has the same value, so every choice gives the same lopsided split.
Hoare's scheme does better. Its inner loops stop on elements equal to the pivot, so equal keys get swapped and the range splits near the middle. That gives O(n log n) on an all-equal array. Even so, it keeps recursing into subarrays whose elements are all the same and are therefore already sorted. That work is wasted.
The better approach is to collect every element equal to the pivot into one block during the pass. That block is finished and never needs to be touched again.
The four regions
Dijkstra's three-way partition, also called the "Dutch national flag" partition, keeps three indices: lt, i, and gt. At the start of each loop iteration the range a[lo..hi] is split into four regions.
| Region | Indices | Contents |
|---|---|---|
| Less | `a[lo .. lt-1]` | elements `< pivot` |
| Equal | `a[lt .. i-1]` | elements `== pivot` |
| Unknown | `a[i .. gt]` | not yet examined |
| Greater | `a[gt+1 .. hi]` | elements `> pivot` |
At the start, lt = lo, i = lo + 1, and gt = hi. The Equal region holds only the pivot itself at a[lo], and everything else is Unknown. Each iteration takes a[i], the first Unknown element, and moves it into the correct region, so the Unknown region gets smaller. The loop ends when the Unknown region is empty, which happens when i > gt.
The implementation
def quicksort3(a, lo, hi):
if lo >= hi:
return
pivot = a[lo]
lt, i, gt = lo, lo + 1, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
quicksort3(a, lo, lt - 1)
quicksort3(a, gt + 1, hi)
data = [3, 5, 3, 1, 3, 7, 3]
quicksort3(data, 0, len(data) - 1)
print(data) # [1, 3, 3, 3, 3, 5, 7]The two recursive calls skip the whole range lt..gt. All of those elements equal the pivot and are already in their final positions.
Why the branches move the indices differently
The difference between the less-than and greater-than branches is where most bugs come from.
- Less than: the element swapped out of
a[lt]is the first element of the Equal region. It is a known pivot-equal value, and it moves to positioni, which is the new end of the Equal region. Both elements are now classified, so bothltandiadvance. - Greater than: the element swapped in from
a[gt]comes from the Unknown region and has never been examined. Onlygtmoves.istays where it is so that the next iteration examines the element that just arrived. - Equal: the element is already at the end of the Equal region, so only
iadvances.
The less-than branch is safe because the Equal region is never empty. It starts with the pivot, and i > lt always holds. So a[lt] is always equal to the pivot.
Tracing an example
Here is the partition step on [3, 5, 3, 1, 3, 7, 3] with pivot = 3.
| Step | `a[i]` | Action | Array after | lt | i | gt |
|---|---|---|---|---|---|---|
| start | `[3, 5, 3, 1, 3, 7, 3]` | 0 | 1 | 6 | ||
| 1 | 5 | greater: swap with `a[6]` | `[3, 3, 3, 1, 3, 7, 5]` | 0 | 1 | 5 |
| 2 | 3 | equal | `[3, 3, 3, 1, 3, 7, 5]` | 0 | 2 | 5 |
| 3 | 3 | equal | `[3, 3, 3, 1, 3, 7, 5]` | 0 | 3 | 5 |
| 4 | 1 | less: swap with `a[0]` | `[1, 3, 3, 3, 3, 7, 5]` | 1 | 4 | 5 |
| 5 | 3 | equal | `[1, 3, 3, 3, 3, 7, 5]` | 1 | 5 | 5 |
| 6 | 7 | greater: swap with itself | `[1, 3, 3, 3, 3, 7, 5]` | 1 | 5 | 4 |
The loop stops because i = 5 > gt = 4. The four 3s fill indices 1 to 4. Recursion continues only on [1] and [7, 5]. In step 1, i stays at 1 after the swap, and the 3 that arrived there is examined in step 2.
Measuring the difference
The script below counts how many elements each partition examines on an all-equal array of 500 elements. The size is small enough that the Lomuto version stays under Python's default recursion limit.
import random
def lomuto_sort(a, lo, hi, count):
if lo < hi:
pivot = a[hi]
i = lo
for j in range(lo, hi):
count[0] += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
lomuto_sort(a, lo, i - 1, count)
lomuto_sort(a, i + 1, hi, count)
def three_way_sort(a, lo, hi, count):
if lo >= hi:
return
pivot = a[lo]
lt, i, gt = lo, lo + 1, hi
while i <= gt:
count[0] += 1
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
three_way_sort(a, lo, lt - 1, count)
three_way_sort(a, gt + 1, hi, count)
n = 500
for name, sort in [("lomuto", lomuto_sort), ("three-way", three_way_sort)]:
count = [0]
sort([7] * n, 0, n - 1, count)
print(name, count[0])
# lomuto 124750
# three-way 499
# Sanity check on random input with few distinct keys
xs = [random.randint(0, 4) for _ in range(10000)]
ys = xs[:]
three_way_sort(ys, 0, len(ys) - 1, [0])
assert ys == sorted(xs)
print("ok")On the all-equal input, Lomuto examines 1 + 2 + … + 499 = 124,750 elements. The three-way version makes one pass of 499 steps and does not recurse.
Cost model and edge cases
Here is how the three-way partition behaves on different kinds of input.
- All keys equal: one pass, so the sort takes O(n) time with O(1) recursion depth.
- k distinct keys: each key value can be chosen as a pivot at most once, because all of its copies end up in the Equal block on that pass. With a random pivot, the expected cost is O(n log k). More precisely, Sedgewick showed the cost is within a constant factor of the entropy lower bound for sorting by comparisons.
- All keys distinct: the Equal region holds only the pivot, so the algorithm does the same job as a two-way quicksort. It does somewhat more swaps than Hoare's scheme, because every less-than element is swapped even when it is already on the correct side.
Three-way partitioning does not fix pivot choice. With pivot = a[lo], an already sorted array of distinct keys still takes O(n²) time. The usual remedy is to swap a randomly chosen element into a[lo] before reading the pivot, using the same idea as randomized_partition but targeting the first slot instead of the last.
Like the other in-place partitions, the three-way partition is not stable. The swap with gt moves elements past others that compare equal to them.
Exercises
Exercise
Suppose you change the greater-than branch to a[i], a[gt] = a[gt], a[i]; gt -= 1; i += 1. Find a three-element input on which quicksort3 then returns an unsorted result, and explain why.
Show answer
Use [2, 3, 1]. With pivot 2, i = 1 and gt = 2. a[1] = 3 is greater, so it is swapped with a[2], giving [2, 1, 3], and gt becomes 1. The buggy code also sets i to 2, which ends the loop before the 1 at index 1 is examined. Then lt = 0 and gt = 1, so the recursion covers only the empty left range and index 2. The result [2, 1, 3] is not sorted. The 1 came from the Unknown region and was never classified.
Exercise
On an input of n elements where every key is either 0 or 1, and both values appear, how many partition passes does quicksort3 make at most? What is its total running time?
Show answer
The first pass puts every copy of the pivot value into the Equal block. The remaining side holds only copies of the other value, and the pass on it finishes in one sweep with no further recursion. That makes two passes that do real work, with empty calls after them, so the total time is O(n).
Exercise
Why is it safe to advance i in the less-than branch, even though the element swapped into position i comes from elsewhere in the array?
Show answer
The element comes from a[lt], the first slot of the Equal region. That region always contains at least the pivot, because i > lt holds throughout the loop. So the incoming element is known to equal the pivot and already belongs at the end of the Equal region.