Sub topic 11
Pattern-Defeating Quicksort
This chapter assumes you have read the introsort chapter. You should know how quicksort partitions around a pivot, why a bad pivot leads to O(n²) time, and how introsort falls back to heapsort. Pattern-defeating quicksort (pdqsort) was introduced by Orson Peters in 2016. It keeps introsort's worst-case guarantee and adds checks that make common real-world inputs faster.
What pdqsort Adds to Introsort
Introsort counts recursion depth and gives up on quicksort after about 2·log₂ n levels. pdqsort counts bad partitions instead. A partition is bad when the smaller side holds less than one eighth of the elements. This measures pivot quality directly, so pdqsort can react earlier and in a more targeted way.
| Technique | What it detects | What pdqsort does |
|---|---|---|
| Small range | Fewer than about 24 elements | Insertion sort |
| Pivot choice | Size of the range | Median of three, or "ninther" (median of medians of three) for large ranges |
| Bad partition | Smaller side under n/8 | Swaps a few elements to break the pattern, then decrements a counter |
| Too many bad partitions | Counter reaches zero (it starts at log₂ n) | Heapsort for that range |
| Pivot equals predecessor | Many duplicate keys | Groups all elements equal to the pivot and skips them |
| No swaps during partition | Range was probably already sorted | Tries a partial insertion sort and abandons it after 8 moves |
The equal-keys check has the biggest effect on real data. After a partition, every element to the right of a pivot is greater than or equal to it. If the next pivot equals that earlier pivot (its predecessor), every element that is not greater than the new pivot must be equal to it. pdqsort moves those elements left and never touches them again. With k distinct keys, the sort runs in O(n·k) time. For very few distinct values, that is close to linear.
Production versions also use block partitioning, taken from BlockQuicksort. They buffer comparison results in small arrays so the CPU avoids unpredictable branches. This only pays off when comparisons are cheap, such as integers.
A Readable Sketch in Python
The sketch below implements the small-range cutoff, the bad-partition counter, the pattern breaking, the heapsort fallback and the equal-keys check. To stay short, it uses a simple Lomuto partition and leaves out block partitioning and the partial insertion sort.
import heapq
import random
INSERTION_THRESHOLD = 24
def insertion_sort(a, lo, hi):
for i in range(lo + 1, hi):
x = a[i]
j = i - 1
while j >= lo and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def heap_sort(a, lo, hi):
part = a[lo:hi]
heapq.heapify(part)
a[lo:hi] = [heapq.heappop(part) for _ in range(len(part))]
def partition(a, lo, hi, take_equal):
# Pivot is a[lo]. Returns its final index p.
pivot = a[lo]
i = lo
for j in range(lo + 1, hi):
if a[j] < pivot or (take_equal and a[j] == pivot):
i += 1
a[i], a[j] = a[j], a[i]
a[lo], a[i] = a[i], a[lo]
return i
def _sort(a, lo, hi, bad_allowed, has_pred):
while hi - lo > INSERTION_THRESHOLD:
mid = (lo + hi) // 2
m = sorted([lo, mid, hi - 1], key=lambda k: a[k])[1]
a[lo], a[m] = a[m], a[lo]
# Pivot equals the predecessor: everything <= pivot equals it.
if has_pred and not (a[lo - 1] < a[lo]):
lo = partition(a, lo, hi, take_equal=True) + 1
continue
p = partition(a, lo, hi, take_equal=False)
left, right = p - lo, hi - p - 1
if min(left, right) < (hi - lo) // 8:
bad_allowed -= 1
if bad_allowed == 0:
heap_sort(a, lo, hi)
return
# Break patterns by swapping a few elements inside each side.
for s, e in ((lo, p), (p + 1, hi)):
if e - s >= INSERTION_THRESHOLD:
q = (e - s) // 4
a[s], a[s + q] = a[s + q], a[s]
a[e - 1], a[e - 1 - q] = a[e - 1 - q], a[e - 1]
_sort(a, lo, p, bad_allowed, has_pred)
lo, has_pred = p + 1, True
insertion_sort(a, lo, hi)
def pdqsort(a):
_sort(a, 0, len(a), len(a).bit_length(), False)
for data in ([random.randrange(5) for _ in range(10000)],
list(range(5000)), list(range(5000, 0, -1)), [7] * 5000):
expected = sorted(data)
pdqsort(data)
assert data == expected
print("ok")Where You Meet It
Go has used pdqsort for sort.Sort, sort.Slice and slices.Sort since Go 1.19. Rust's sort_unstable used pdqsort until Rust 1.81. Its replacement, ipnsort, is built on pdqsort's ideas. Boost.Sort provides boost::sort::pdqsort for C++. The library survey chapter covers these functions in detail.
Exercise
An array of one million integers contains only the values 0, 1 and 2. Why does pdqsort finish this array in roughly linear time while a plain median-of-three quicksort with a two-way partition can slow down badly?
Show answer
In a two-way partition, keys equal to the pivot all land on one side. With so many duplicates, partitions come out lopsided, and the same equal keys get partitioned again at every level. pdqsort checks whether the new pivot equals its predecessor. When it does, the sort groups every element equal to the pivot and never revisits them. Each of the 3 distinct values costs about one pass, so the total is O(n·k) with k = 3.
Exercise
In the sketch, why is it safe to treat every element not greater than the pivot as equal to it when the pivot equals a[lo - 1]?
Show answer
a[lo - 1] was a pivot of an earlier partition, so every element in a[lo:hi] is greater than or equal to it. If the new pivot equals that predecessor, an element not greater than the pivot is both >= and <= the same value, so it must be equal.