Sub topic 8
Choosing a Good Pivot
This chapter assumes you can read the in-place Lomuto quicksort from earlier chapters, know why a sorted input pushes a last-element pivot into O(n²) time, and are comfortable with Big-O notation and recursion. Here we look at what makes a pivot "good" and compare the main strategies for picking one. Later chapters cover randomized quicksort and median-of-three in detail.
What a Pivot Has to Do
The partition step always costs linear time in the size of the subarray. The pivot only decides how that subarray splits into two parts. All of quicksort's performance comes from that split.
- If the pivot is the exact median, each level of recursion halves the problem. That gives about log₂ n levels and O(n log n) total work.
- If the pivot is the minimum or maximum, one side is empty and the other has n − 1 elements. That gives n levels and O(n²) total work.
A good pivot strategy balances three things:
- Split quality. How close the pivot tends to land to the median.
- Selection cost. How much work it takes to choose the pivot, paid on every partition call.
- Predictability. Whether some input, or someone who knows your strategy, can reliably force bad splits.
"Good enough" is far from perfect
You do not need the median. Suppose every split is at worst 25% / 75%. The larger side shrinks by a factor of 3/4 at each level, so the depth is at most log₄/₃ n ≈ 2.41 log₂ n. That is still O(log n) levels of O(n) work each, so O(n log n) overall. Even a fixed 1% / 99% split keeps the depth logarithmic, though with a large constant.
Half of all elements fall between the 25th and 75th percentiles. So a pivot picked uniformly at random is "good enough" with probability 1/2. This fact is the basis of the randomized analysis in the next chapter.
The Main Strategies
| Strategy | Selection cost | Bad inputs | Typical use |
|---|---|---|---|
| First or last element | O(1) | Sorted, reverse-sorted, nearly sorted | Teaching code only |
| Middle element | O(1) | Specially constructed "organ-pipe" patterns; harmless on sorted data | Simple implementations |
| Random element | O(1) plus an RNG call | None that are fixed in advance; bad luck has very low probability | General-purpose, adversarial settings |
| Median-of-three (first, middle, last) | A few comparisons | Deliberately crafted "median-of-3 killer" sequences | Many library sorts |
| Ninther (median of three medians-of-three) | About 12 comparisons | Harder to attack, still deterministic | Large arrays in tuned libraries |
| Median of medians | O(n), large constant | None: O(n log n) worst case is guaranteed | Rare in practice; mostly theoretical |
Two points from the table are worth stating directly.
- Any deterministic rule has a worst-case input. If the pivot depends only on the array contents and positions, someone can build an array that makes the rule pick a bad element at every level. Median-of-three makes this harder, but it is still possible.
- Exact medians are too expensive. The median-of-medians algorithm finds a true median in linear time, which guarantees O(n log n) for quicksort. Its constant factor is so large that a randomized or sampled pivot is faster on almost all real inputs.
A Pluggable Experiment
The code below separates pivot choice from partitioning. A chooser function returns the index of the pivot. That element is swapped into the last position, and then the standard Lomuto partition runs. The counter records element comparisons inside partition, which is a good stand-in for running time.
import random
def partition(a, lo, hi, counter):
pivot = a[hi]
i = lo
for j in range(lo, hi):
counter[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, lo, hi, choose, counter):
if lo < hi:
k = choose(a, lo, hi)
a[k], a[hi] = a[hi], a[k]
p = partition(a, lo, hi, counter)
quicksort(a, lo, p - 1, choose, counter)
quicksort(a, p + 1, hi, choose, counter)
def choose_last(a, lo, hi):
return hi
def choose_middle(a, lo, hi):
return (lo + hi) // 2
def choose_random(a, lo, hi):
return random.randint(lo, hi)
def choose_median3(a, lo, hi):
mid = (lo + hi) // 2
trio = sorted([(a[lo], lo), (a[mid], mid), (a[hi], hi)])
return trio[1][1]
n = 400
inputs = {
"random": random.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"all-equal": [7] * n,
}
choosers = {
"last": choose_last,
"middle": choose_middle,
"random": choose_random,
"median3": choose_median3,
}
for cname, choose in choosers.items():
for iname, data in inputs.items():
a = list(data)
counter = [0]
quicksort(a, 0, len(a) - 1, choose, counter)
assert a == sorted(data)
print(f"{cname:8} {iname:10} {counter[0]:>6}")The array size is kept at 400 because the quadratic cases recurse about n levels deep. Python's default recursion limit is 1000, so much larger sorted inputs would crash the last-element version. The chapter on bounding recursion depth deals with this.
Reading the results
The exact numbers change from run to run because of the random input and the random chooser. The pattern does not change:
- last on sorted or reversed input does exactly 399 + 398 + … + 1 = 79,800 comparisons. Each partition removes only the pivot.
- middle, random, and median3 on sorted and reversed input stay in the low thousands, roughly 3,000 to 5,000. That is about n log₂ n.
- On random input, all four strategies land in that same low-thousands range. Pivot choice barely matters when the data has no structure.
- On all-equal input, every strategy does 79,800 comparisons.
That last row is the most important lesson in the experiment.
How Pivot Choice Fails
Pivot strategies fail in a few distinct ways, and it helps to keep them apart.
- Structural alignment. Real data is often sorted, nearly sorted, or appended in order, for example timestamps or IDs. A fixed-position pivot lines up exactly with that structure. This is the most common failure in real code, and middle, sampled, or random pivots all fix it.
- Adversarial input. If an attacker can supply the data to a server-side sort, they can build a killer sequence for any deterministic rule. That turns each request into O(n²) CPU work, which works as a denial-of-service vector. Randomization with a seed the attacker cannot predict, or an introsort fallback, closes this hole.
- Duplicate-heavy data. As the experiment shows, this is a partitioning problem rather than a pivot problem.
- Selection overhead. Sampling more elements gives better splits but costs comparisons on every call. Most of those calls are on small subarrays, where the extra cost outweighs the benefit. Libraries therefore scale the sample size with the subarray size: no sampling for tiny ranges, median-of-three for medium ranges, and the ninther for large ones.
Decision Criteria
When you choose a strategy, ask these questions in order:
- Who controls the input? If an outside party does, use a deterministic rule only together with a worst-case fallback.
- What structure is common in your data? Sorted and nearly sorted runs rule out first-element and last-element pivots.
- How large are the subarrays? Sampling pays off on large ranges and wastes time on small ones.
- Do you need reproducibility? Random pivots give different comparison counts on each run, which can make benchmarking and debugging harder. You can seed the RNG for tests, but in production keep the seed unpredictable.
- Do you need a guarantee or a good expected time? Pivot choice alone gives good expected behavior. A guarantee needs a fallback such as introsort.
Exercise
A colleague's quicksort uses the first element as the pivot. It is fast in benchmarks on random data, but it times out in production, where it sorts log records already ordered by timestamp. Explain the cause, name two pivot strategies that fix it, and say which input type would still make both of those fixes quadratic with a Lomuto partition.
Show answer
On data already sorted by timestamp, the first element is the minimum of every subarray. Each partition then removes only the pivot, which gives n levels and about n²/2 comparisons. A middle-element pivot or a median-of-three pivot picks the true median of a sorted range and restores O(n log n). A random pivot also works. All of these still go quadratic on input with many equal keys, such as every record sharing one timestamp. Lomuto's strict < test sends all equal elements to one side, so the partition must be changed to three-way partitioning.
Exercise
Suppose a pivot rule always produces a split no worse than 10% / 90%. What is the recursion depth in terms of n, and what is the total running time?
Show answer
The larger side shrinks by a factor of 0.9 per level, so the depth is at most log base 10/9 of n, which is about 6.6 log₂ n. That is O(log n). Each level does O(n) partition work in total, so the running time is O(n log n), with a larger constant than an even split.