Sub topic 11
Pattern-Defeating Quicksort
This chapter assumes you have read the introsort chapter. It also assumes you can follow recursive partition code and Big-O arguments, and you know that quicksort is unstable. Pattern-defeating quicksort, usually shortened to pdqsort, was published by Orson Peters in 2016. It keeps introsort's main promise: quicksort speed in the common case, and an O(n log n) worst case backed by a heapsort fallback. It adds several cheap checks that recognize common input patterns and either exploit them or break them up.
Where pdqsort Sits
Introsort uses three algorithms: quicksort for most of the work, insertion sort for small ranges, and heapsort when recursion goes too deep. Pdqsort keeps all three. It changes how it chooses pivots, how it handles duplicates, how it notices already-sorted data, and how it decides that quicksort is going badly.
| Concern | Introsort | Pdqsort |
|---|---|---|
| Worst-case guard | Recursion depth limit of about 2·log2(n) | Limit of about log2(n) *bad partitions* |
| Pivot choice | Median of 3 | Median of 3, or Tukey's ninther for ranges above 128 elements |
| Many equal keys | Can degrade, depending on the partition scheme | Groups equal keys in one pass: O(n·k) for k distinct values |
| Already-sorted input | O(n log n) | O(n), detected after the first partition |
| Adversarial patterns | Falls back to heapsort | Shuffles a few elements first, then falls back to heapsort |
| Stable | No | No |
The Main Loop
The flowchart below shows one call on a range. The real implementation loops on one side of each partition and recurses on the other.
The Heuristics, One at a Time
Pivot selection
For ranges up to 128 elements, pdqsort sorts the first, middle and last elements and uses the median. Larger ranges use Tukey's ninther: three medians of three taken from different parts of the range, then the median of those three. The ninther costs about 12 comparisons and gives a much better estimate of the true median. A better estimate means fewer unbalanced partitions.
Equal keys and the predecessor trick
Every subrange except the leftmost one has a predecessor, the element just before it in the array. Earlier partitioning guarantees that the predecessor is less than or equal to every element in the subrange. Suppose the chosen pivot is not greater than the predecessor. Then the pivot equals the predecessor, and no element in the range can be smaller than the pivot.
In that case pdqsort calls partition_left, which puts every element equal to the pivot on the left and every greater element on the right. The left part now holds only copies of one value, so it is already sorted and is never visited again. Each distinct value gets removed in a single linear pass, which gives O(n·k) total work for k distinct keys. An input with four distinct values sorts in linear time.
Detecting sorted input
partition_right reports whether it needed any swaps. If it needed none, the range may already be sorted, so pdqsort runs a partial insertion sort on each side. This is an ordinary insertion sort that gives up after 8 element moves in total. On sorted data it completes in one linear scan and the sort ends. On data that only happened to partition cleanly, it gives up after a few moves, and the extra cost is small.
Bad partitions
A partition is bad when its smaller side holds fewer than n/8 of the elements. Pdqsort starts with a budget of about log2(n) bad partitions. Each bad partition spends one credit and swaps a few elements at fixed quarter positions inside each side. Those swaps break up patterns, such as organ-pipe arrays, that keep fooling the pivot choice. If the budget runs out, the range is heapsorted. A run of bad partitions usually means the input is adversarial, not just unlucky. Counting bad partitions catches that sooner than a depth limit does, and it also lets the algorithm tolerate a few bad partitions that a depth limit would wrongly penalize.
Branchless block partitioning
When comparisons are cheap and have no side effects, as with integers under the default <, the C++ reference version uses the block partitioning technique from BlockQuicksort (Edelkamp and Weiss). It compares a block of elements, stores the positions of misplaced ones in small offset buffers, and swaps them in a separate step. The comparison loop has no data-dependent branches, so the CPU does not pay for branch mispredictions on random data. With an expensive or user-supplied comparator, this gives little benefit, and the plain partition loop is used.
A Working Python Model
The code below implements every heuristic above except block partitioning, which only pays off in compiled code. Unlike the real algorithm, its heapsort fallback copies the range into a temporary list, which keeps the code short.
import heapq
import random
INSERTION_THRESHOLD = 24
NINTHER_THRESHOLD = 128
PARTIAL_LIMIT = 8
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 partial_insertion_sort(a, lo, hi):
"""Insertion sort that gives up after PARTIAL_LIMIT moves. True means sorted."""
moves = 0
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
moves += i - 1 - j
if moves > PARTIAL_LIMIT:
return False
return True
def heap_sort(a, lo, hi):
heap = a[lo:hi]
heapq.heapify(heap)
for i in range(lo, hi):
a[i] = heapq.heappop(heap)
def sort3(a, i, j, k):
if a[j] < a[i]:
a[i], a[j] = a[j], a[i]
if a[k] < a[j]:
a[j], a[k] = a[k], a[j]
if a[j] < a[i]:
a[i], a[j] = a[j], a[i]
def choose_pivot(a, lo, hi):
"""Move a median estimate to a[lo]."""
n = hi - lo
mid = lo + n // 2
if n > NINTHER_THRESHOLD:
sort3(a, lo, mid, hi - 1)
sort3(a, lo + 1, mid - 1, hi - 2)
sort3(a, lo + 2, mid + 1, hi - 3)
sort3(a, mid - 1, mid, mid + 1)
else:
sort3(a, lo, mid, hi - 1)
a[lo], a[mid] = a[mid], a[lo]
def partition_right(a, lo, hi):
"""Elements < pivot go left, >= pivot go right. Returns (pivot_pos, no_swaps)."""
pivot = a[lo]
i, j = lo + 1, hi - 1
while i <= j and a[i] < pivot:
i += 1
while i <= j and not (a[j] < pivot):
j -= 1
no_swaps = i > j
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
while i <= j and a[i] < pivot:
i += 1
while i <= j and not (a[j] < pivot):
j -= 1
p = i - 1
a[lo], a[p] = a[p], a[lo]
return p, no_swaps
def partition_left(a, lo, hi):
"""Elements <= pivot go left, > pivot go right. Returns pivot_pos."""
pivot = a[lo]
i, j = lo + 1, hi - 1
while True:
while i <= j and not (pivot < a[i]):
i += 1
while i <= j and pivot < a[j]:
j -= 1
if i >= j:
break
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
p = i - 1
a[lo], a[p] = a[p], a[lo]
return p
def _pdq(a, lo, hi, bad_allowed, leftmost):
while True:
n = hi - lo
if n < INSERTION_THRESHOLD:
insertion_sort(a, lo, hi)
return
choose_pivot(a, lo, hi)
# Predecessor equals pivot: no element here is smaller, so group the equal ones.
if not leftmost and not (a[lo - 1] < a[lo]):
lo = partition_left(a, lo, hi) + 1
continue
p, no_swaps = partition_right(a, lo, hi)
left_n, right_n = p - lo, hi - p - 1
if min(left_n, right_n) < n // 8:
bad_allowed -= 1
if bad_allowed == 0:
heap_sort(a, lo, hi)
return
if left_n >= INSERTION_THRESHOLD:
q = left_n // 4
a[lo], a[lo + q] = a[lo + q], a[lo]
a[p - 1], a[p - q] = a[p - q], a[p - 1]
if right_n >= INSERTION_THRESHOLD:
q = right_n // 4
a[p + 1], a[p + 1 + q] = a[p + 1 + q], a[p + 1]
a[hi - 1], a[hi - q] = a[hi - q], a[hi - 1]
elif no_swaps:
if partial_insertion_sort(a, lo, p) and partial_insertion_sort(a, p + 1, hi):
return
# Recurse on the smaller side, loop on the larger, to bound stack depth.
if left_n < right_n:
_pdq(a, lo, p, bad_allowed, leftmost)
lo, leftmost = p + 1, False
else:
_pdq(a, p + 1, hi, bad_allowed, False)
hi = p
def pdqsort(a):
if len(a) > 1:
_pdq(a, 0, len(a), len(a).bit_length(), True)
return a
if __name__ == "__main__":
rng = random.Random(1)
cases = {
"random": [rng.random() for _ in range(10_000)],
"sorted": list(range(10_000)),
"reversed": list(range(10_000, 0, -1)),
"few distinct": [rng.randrange(4) for _ in range(10_000)],
"organ pipe": list(range(5_000)) + list(range(5_000, 0, -1)),
}
for name, data in cases.items():
assert pdqsort(list(data)) == sorted(data), name
print("all cases sorted correctly")Trace the sorted case to see the linear path. The ninther leaves sorted data unchanged, and the swap moves the median to a[lo] and the smallest element to the middle. partition_right finds nothing to swap. Its final swap puts the median back in the middle and the smallest element back at the front, so the array is sorted again. Both partial insertion sorts then finish without a single move.
Who Uses It
| Library | Function | Algorithm |
|---|---|---|
| Rust | `slice::sort_unstable` | pdqsort from 1.20 to 1.80; ipnsort, a pdqsort descendant, since 1.81 |
| Go | `sort.Sort`, `sort.Slice`, `slices.Sort` | pdqsort since Go 1.19 |
| Boost | `boost::sort::pdqsort` | The reference implementation |
| C++ standard libraries | `std::sort` | Mostly introsort variants; the standard requires only O(n log n) |
Go's version adds one refinement. While choosing a pivot, it notes whether the sampled elements were in descending order. If they were, it reverses the range first, so reverse-sorted input also takes the linear path.
Edge Cases and Gotchas
- Broken comparators. The partition loops trust that
<is a strict weak ordering. The bounds checks in this Python model stop an inconsistent comparator from running past the range, but the output will not be sorted. Compiled implementations that skip bounds checks for speed can do worse. Rust guards against this and may panic or return an unsorted slice, but it never reads memory out of bounds. - Leftmost ranges. The leftmost range has no predecessor, so the code must not read
a[lo - 1]there. Theleftmostflag handles this. - Linear time needs real structure. The no-swap check catches fully sorted ranges. Data that is "mostly sorted" with scattered disorder usually fails the 8-move limit and is sorted in O(n log n). Timsort handles that kind of input better.
- Equal keys still move.
partition_leftgroups equal elements, but it does not keep them in input order. On records that compare equal by key, the output order of those records is arbitrary.
Exercise
In the subrange [5, 7, 5, 9, 5, 6] the predecessor is 5, and the chosen pivot is 5. Which partition function runs, what does the left part contain afterward, and why is the left part never sorted again?
Show answer
partition_left runs, because the predecessor 5 is not less than the pivot 5. Afterward the left part contains only 5s. Every element of the subrange is at least the predecessor, so anything less than or equal to the pivot must equal 5. A range of identical values is already sorted, and the algorithm continues only with the part holding 6, 7 and 9.
Exercise
Why does pdqsort limit the number of bad partitions instead of limiting recursion depth as introsort does, and what does it do before falling back to heapsort?
Show answer
A depth limit counts every level of recursion, including well-balanced ones, while the bad-partition count only counts the unbalanced partitions that actually signal trouble. This lets pdqsort tolerate occasional bad luck and still detect adversarial input after about log2(n) bad partitions. Before spending its last credit, it swaps a few elements at quarter positions on each side to break patterns that keep fooling the pivot choice.
Exercise
Change partialinsertionsort so it never gives up, by removing the move limit. Which input becomes slower, and why?
Show answer
Inputs that partition with no swaps but are far from sorted become slower. Without the limit, the "maybe sorted" check can become a full insertion sort costing O(n^2) on that range. The 8-move limit keeps a wrong guess cheap.