Sub topic 7
Handling Duplicates With Three-Way Partitioning
This chapter assumes you already know the in-place iterative quickselect with Lomuto partitioning from earlier chapters. You should also be comfortable with loop invariants and Big-O notation. Here we fix one specific weakness of that version: input with many repeated values.
Why Duplicates Hurt Two-Way Partitioning
Lomuto partitioning compares each element with a[i] < pivot. Every element equal to the pivot fails that test, so it lands on the right side. If the array is [7, 7, 7, 7, 7], every pivot is 7. Nothing is strictly smaller, so the pivot always ends at index lo, and each pass shrinks the range by exactly one element.
That makes the running time n + (n − 1) + (n − 2) + … = O(n²). A random pivot does not help, because every candidate pivot has the same value. Real data often looks like this: ratings from 1 to 5, HTTP status codes, boolean flags, or timestamps rounded to the day.
The Three-Way Idea
Three-way partitioning splits the range into three groups instead of two: less than the pivot, equal to the pivot, and greater than the pivot. Edsger Dijkstra described this scheme as the Dutch national flag problem. After one pass, the whole equal block is in its final sorted position. If k falls inside that block, the answer is the pivot. Otherwise, the search continues on one side, and the entire equal block is excluded from it.
The scheme uses three indices, lt, i, and gt, and keeps this invariant during the scan:
| Region | Contents |
|---|---|
| `a[lo:lt]` | less than pivot |
| `a[lt:i]` | equal to pivot |
| `a[i:gt+1]` | not yet examined |
| `a[gt+1:hi+1]` | greater than pivot |
Each step looks at a[i] and moves it into the region where it belongs. The unexamined region shrinks by one on every step, so a single pass takes O(n) time.
The Implementation
import random
def quickselect3(a, k):
"""In-place quickselect with three-way (Dutch national flag) partitioning."""
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
while lo < hi:
pivot = a[random.randint(lo, hi)]
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
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
# Now a[lo:lt] < pivot, a[lt:gt+1] == pivot, a[gt+1:hi+1] > pivot
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
return a[k]
print(quickselect3([5, 5, 5, 1, 5, 9, 5], 3)) # 5
print(quickselect3([7] * 10, 4)) # 7
print(quickselect3([3, 1, 2, 3, 1, 2], 0)) # 1This version stores the pivot's value, not its index. Swaps move elements around during the scan, so an index would stop pointing at the pivot partway through, but the value stays the same.
Here is what happens with [5, 5, 5, 1, 5, 9, 5] and k = 3. Suppose the random pivot is 5. After the scan, the array is [1, 5, 5, 5, 5, 5, 9], with lt = 1 and gt = 5. Since 1 ≤ 3 ≤ 5, the function returns 5 after one pass. On [7] * 10, every element is equal, so lt stays at 0 and gt stays at 9 after one pass. The function returns immediately, in linear time rather than quadratic.
Common Errors
- Advancing
iafter a swap withgt. The element that arrives ata[i]came from the unexamined region, so it still has to be classified. Ifimoves past it, that element can end up in the wrong group. - Using the pivot's index after swaps. Read the value once, before the loop starts.
- Checking
kagainstltandgtoff by one. The equal block isa[lt..gt]inclusive, so the tests arek < ltandk > gt. - Assuming it is always faster. On arrays of distinct values, three-way partitioning does slightly more comparisons per element than Lomuto. In exchange, the worst case on duplicate-heavy input goes away.
Exercise
In the a[i] > pivot branch, why does i stay where it is while it advances in the a[i] < pivot branch?
Show answer
When a[i] is swapped with a[gt], the element that arrives at position i comes from the unexamined region, so it still has to be compared with the pivot. When a[i] is swapped with a[lt], the element that arrives is from the equal region (or is a[i] itself when lt == i), so it is already classified and i can move on.
Exercise
How many partition passes does quickselect3 make on an array of n identical values, and how many does Lomuto-based quickselect need for the worst-case k = n - 1?
Show answer
quickselect3 makes one pass: every element joins the equal block, so lt = lo, gt = hi, and any valid k falls inside it. Lomuto-based quickselect places each pivot at index lo, so each pass removes only one element. Reaching k = n - 1 takes n - 1 passes, which is O(n^2) work in total.