Sub topic 8
Choosing a Good Pivot
This chapter assumes you know the Lomuto partition scheme, the recursive structure of quicksort, and why a lopsided split costs O(n²). Here we look at the pivot rules you can choose from and how to judge between them. Later chapters cover randomized pivots and median-of-three in detail.
What a Pivot Rule Has to Do
The pivot determines the split. If the pivot lands near the median, each partition is about half the size of the range, and the recursion is O(log n) levels deep. If it lands near an extreme, one side is nearly empty, and the depth grows toward n.
A pivot rule therefore has to balance two costs:
- Quality: how close to the median the pivot usually lands.
- Overhead: how much work it takes to choose the pivot on every call.
Finding the exact median guarantees perfect splits, but it costs too much at every level. Practical rules settle for a pivot that is good enough most of the time and cheap to compute.
Common Strategies
| Rule | Cost per call | Bad inputs | Notes |
|---|---|---|---|
| First or last element | O(1) | Sorted, reverse-sorted | Simplest rule. Fails on common real data |
| Middle element | O(1) | Specially crafted inputs | Handles sorted data well |
| Random element | O(1) plus an RNG call | None in expectation | Gives an expected O(n log n) on every input |
| Median-of-three | 2 to 3 comparisons | Rare crafted inputs | Better splits on average |
| Exact median (median of medians) | O(n) | None | Guaranteed O(n log n), but the constant factor is too large for most uses |
Measuring the Difference
The pivot rule can be a separate function. The sort swaps the chosen element into position hi and then runs the usual Lomuto partition. This script counts comparisons on input that is already sorted:
import random
def partition(a, lo, hi, count):
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]
return i
def quicksort(a, choose, count, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
r = choose(lo, hi)
a[r], a[hi] = a[hi], a[r]
p = partition(a, lo, hi, count)
quicksort(a, choose, count, lo, p - 1)
quicksort(a, choose, count, p + 1, hi)
rules = {
"last": lambda lo, hi: hi,
"middle": lambda lo, hi: (lo + hi) // 2,
"random": lambda lo, hi: random.randint(lo, hi),
}
n = 400
for name, choose in rules.items():
data = list(range(n))
count = [0]
quicksort(data, choose, count)
assert data == list(range(n))
print(f"{name:>6}: {count[0]} comparisons")On sorted input the last-element rule does exactly n(n−1)/2 = 79,800 comparisons. The middle and random rules each do a few thousand, close to n log₂ n.
Mistakes to Watch For
- Forgetting the swap. Lomuto takes its pivot from
a[hi]. If you choose some other index and don't swap it intohi, the partition uses the wrong pivot. - Testing only on random data. All pivot rules look fine on shuffled input. Also test on sorted data, reverse-sorted data, and data with every element equal.
- Expecting pivot choice to fix duplicates. If every key is equal, every pivot rule produces the same lopsided split under Lomuto. That case needs three-way partitioning.
Exercise
Run the script with the "last" rule on list(range(n, 0, -1)), which is reverse-sorted input. Roughly how many comparisons do you expect, and why?
Show answer
About n(n−1)/2, which is 79,800 for n = 400. The last element is always the minimum of its range, so every partition puts all other elements on one side, and each level of recursion removes only one element.
Exercise
Why do libraries rarely use the exact median as the pivot, even though it guarantees balanced splits?
Show answer
Computing the exact median takes O(n) extra work with a large constant factor at every level. Cheap rules give splits that are nearly as good on typical data and run faster overall.