Sub topic 5
Choosing a Pivot: Random, First Element, and Median-of-Three
Quickselect's speed depends almost entirely on one decision it makes at each step: which element to partition around. This chapter compares three common pivot rules. They are the first (or last) element, a uniformly random element, and the median of three sampled elements. You will run a small experiment that counts comparisons for each rule on different inputs.
This chapter assumes you know the following from earlier chapters:
- How Lomuto partitioning works, through the
partition(a, lo, hi, p)function that placesa[p]at its final sorted index. - The in-place iterative quickselect loop that narrows
a[lo..hi]until indexkis found. - Basic Big-O notation.
The formal expected-time analysis comes in the next chapter. Here the focus is on how each rule behaves in practice and how it fails.
Why the Pivot Decides Everything
Each partition step costs about hi - lo comparisons. After the step, quickselect keeps only the side that contains index k. The pivot's final position therefore decides how much work remains.
- A pivot near the middle of the current range discards about half the elements. The total work becomes roughly n + n/2 + n/4 + …, which is about 2n.
- A pivot at the extreme end discards only itself. The total work becomes roughly n + (n−1) + (n−2) + …, which is about n²/2.
A pivot rule does not need to find the exact median. It only needs to avoid extreme positions most of the time. The three rules below meet that requirement to different degrees.
Making the Pivot Rule Pluggable
To compare the rules fairly, the quickselect below takes the pivot rule as a parameter. Each rule is a function (a, lo, hi, rng) -> index. The partition function also counts comparisons so you can measure the cost of each rule.
import random
def partition(a, lo, hi, p, counter):
"""Lomuto partition of a[lo..hi] around a[p]; returns the pivot's final index."""
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = lo
for i in range(lo, hi):
counter[0] += 1
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store]
return store
def quickselect(a, k, choose_pivot, rng, counter):
"""Return the k-th smallest (0-based) element of a, using choose_pivot."""
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
while True:
if lo == hi:
return a[lo]
p = partition(a, lo, hi, choose_pivot(a, lo, hi, rng), counter)
if k == p:
return a[k]
elif k < p:
hi = p - 1
else:
lo = p + 1
def first_pivot(a, lo, hi, rng):
return lo
def random_pivot(a, lo, hi, rng):
return rng.randint(lo, hi) # inclusive on both ends
def median_of_three(a, lo, hi, rng):
"""Return the index of the median of a[lo], a[mid], a[hi]."""
mid = (lo + hi) // 2
x, y, z = a[lo], a[mid], a[hi]
if x < y:
if y < z:
return mid # x < y < z
elif x < z:
return hi # x < z <= y
else:
return lo # z <= x < y
else:
if x < z:
return lo # y <= x < z
elif y < z:
return hi # y < z <= x
else:
return mid # z <= y <= xThe pivot rule returns an index, not a value. Lomuto partitioning moves that element to a[hi] before scanning, so any rule can plug in without changing partition.
Rule 1: The First (or Last) Element
The simplest rule takes a[lo] (or a[hi]) as the pivot. It needs no extra comparisons and no random number generator. On data in random order, it performs about as well as a random pivot, because a fixed position in a shuffled array holds a random element.
The problem is that real data is rarely shuffled. Already-sorted input, nearly sorted input, and reverse-sorted input are common: log files ordered by timestamp, IDs assigned in sequence, results from an earlier sort. On sorted input, a[lo] is always the smallest element in the range.
Trace this rule on the sorted array [0, 1, 2, …, n−1]:
- The pivot is
a[lo], the minimum. Lomuto swaps it toa[hi], finds no element smaller, and swaps it back. It returnsp = lo. - The array is still sorted. Only one element has been ruled out.
- If
kis in the middle, the loop repeats about n/2 times, and each pass scans almost the whole remaining range.
For n = 2000 and k = 1000, the iteration with lo = j makes 1999 − j comparisons, for j from 0 to 1000. The total is 1,500,499 comparisons. That is about 750 times more than the roughly 2n you would hope for.
Use a fixed-position pivot only when you control the input and know it is shuffled. One example is a teaching implementation run on data you generated randomly yourself.
Rule 2: A Uniformly Random Element
The random rule picks an index uniformly from lo to hi. Its key property is that performance no longer depends on how the input is arranged. A sorted array, a reversed array, and a shuffled array all look the same to the algorithm, because the randomness comes from the generator, not from the data.
Bad runs can still happen. The generator might pick near-extreme pivots several times in a row. But no input reliably causes this, and the chance of a long run of bad pivots shrinks exponentially with its length. The next chapter turns this argument into the expected O(n) bound. For finding the median, the expected number of comparisons with a random pivot is about 3.39n.
The random rule has some practical details to get right.
- Inclusive bounds.
random.randint(lo, hi)includeshi. If you userandom.randrange, you must writerandrange(lo, hi + 1). Writingrandrange(lo, hi)never picks the last element, and it raisesValueErrorwhenlo == hi. - Reproducibility. The global
randommodule produces different runs each time. For tests and benchmarks, pass arandom.Random(seed)instance asrngabove, so a failing case can be replayed exactly. - Adversaries. Python's Mersenne Twister generator is not cryptographically secure. If an attacker can submit inputs to a service and observe enough of its random output, they can in principle predict future pivots and build a slow input. This is rarely a real threat. If it matters, seed per process from
os.urandomor userandom.SystemRandom. Better still, add a worst-case guarantee, which the introselect chapter covers. - Cost. Generating a random number costs more than reading
a[lo], but it happens once per partition, not once per element. Compared with the O(n) scan, the cost is negligible.
Rule 3: Median-of-Three
Median-of-three looks at a[lo], a[mid], and a[hi] and uses the middle one of those three values as the pivot. It costs two or three extra comparisons per partition and needs no random number generator.
It has two advantages:
- Sorted and reverse-sorted input become the best case. On sorted input,
a[mid]is the true median of the range, so every split is perfect. The same n = 2000, k = 1000 run that cost 1.5 million comparisons with the first-element rule now costs a few thousand. - Splits are more balanced on random input. The median of three random samples is less likely to be extreme than a single sample. The chance that the pivot falls in the outer quarter on either side drops from 50% to about 31%. For finding the median, the expected comparison count drops from about 3.39n to about 2.75n.
The weakness of deterministic median-of-three is that it always samples the same three positions. Someone who knows the rule can build an input that places small values at exactly those positions on every round, so every pivot is the second-smallest element of its range. David Musser described such "median-of-3 killer" sequences in 1997, when he introduced introsort and introselect. They make the algorithm quadratic again. Such inputs rarely occur by accident, but they can be built on purpose.
Variants Worth Knowing
- Randomized median-of-three. Choose three random indices and take their median. This keeps the better splits and removes the fixed positions that killer inputs target.
- Ninther (Tukey's median of medians of three). Take three medians-of-three from nine spread-out positions, then take the median of those three. Some library implementations use it on large ranges, where nine reads are cheap compared with the scan. It is not the same as the median-of-medians algorithm in a later chapter, which gives a guarantee. The ninther is only a heuristic.
- Index overflow. In Python,
(lo + hi) // 2is safe. In C, C++, or Java with fixed-width integers, writelo + (hi - lo) / 2so the sum cannot overflow.
Running the Experiment
Add this driver below the code above and run it. It measures each rule on sorted, reversed, and shuffled inputs of size 2000, searching for the median.
def run_experiment(n=2000, seed=42):
rng = random.Random(seed)
shuffled = list(range(n))
rng.shuffle(shuffled)
inputs = {
"sorted": list(range(n)),
"reversed": list(range(n - 1, -1, -1)),
"shuffled": shuffled,
}
rules = {
"first": first_pivot,
"random": random_pivot,
"median3": median_of_three,
}
k = n // 2
print(f"{'rule':<8} {'input':<9} {'comparisons':>12}")
for rule_name, rule in rules.items():
for input_name, data in inputs.items():
a = list(data) # fresh copy: quickselect reorders in place
counter = [0]
result = quickselect(a, k, rule, rng, counter)
assert result == k # values are 0..n-1, so the k-th smallest is k
print(f"{rule_name:<8} {input_name:<9} {counter[0]:>12}")
run_experiment()You should see these patterns. Exact numbers for the random cases change with the seed.
firstonsortedprints exactly 1,500,499. Onreversed, it is also in the hundreds of thousands or more.randomstays in the low thousands on all three inputs, usually somewhere around 3n to 4n.median3is very low onsortedandreversed, and about the same as or a little better thanrandomonshuffled.
The assert line checks correctness. Every rule must return the same answer, and only the cost may differ. A pivot rule that changes the result has a bug, usually an index outside lo..hi.
Choosing a Rule
| Rule | Extra cost per partition | Sorted or reversed input | Shuffled input | Resists crafted input | Deterministic |
|---|---|---|---|---|---|
| First or last element | None | Quadratic | Expected linear | No | Yes |
| Random element | One random number | Expected linear | Expected linear | Yes, unless the generator is predictable | No |
| Median-of-three (fixed) | 2–3 comparisons | Best case | Expected linear, fewer comparisons | No | Yes |
| Median-of-three (random samples) | 3 random numbers, 2–3 comparisons | Expected linear | Expected linear, fewer comparisons | Yes, unless the generator is predictable | No |
Use these rules of thumb:
- For general-purpose code, use a random pivot, or randomized median-of-three if you want fewer comparisons.
- If you need deterministic, repeatable behavior without a seeded generator, use fixed median-of-three. Pair it with a fallback that guarantees worst-case linear time, as introselect does.
- Avoid fixed-position pivots unless you know the input is shuffled.
Exercises
Exercise
A colleague replaces rng.randint(lo, hi) with rng.randrange(lo, hi) in random_pivot. Describe two problems this causes.
Show answer
First, randrange(lo, hi) excludes hi, so the last element of the range can never be chosen as the pivot. The pivot is no longer uniform, though the result stays correct. Second, when the range has one element (lo == hi), randrange(lo, lo) raises ValueError. The loop above returns before calling the rule in that case, but a recursive version that calls the rule first would crash. The fix is randrange(lo, hi + 1), or keeping randint(lo, hi).
Exercise
Using the first-element rule, how many comparisons does the experiment's quickselect make to find k = 0 (the minimum) in a sorted array of n = 2000? How many does it make for k = 1999 (the maximum)?
Show answer
For k = 0, the first partition puts the pivot (the minimum) at index 0, which equals k, so the loop stops after one pass of 1999 comparisons. For k = 1999, each pass with lo = j makes 1999 − j comparisons and returns p = j. The loop runs for j = 0 to 1998, then stops when lo == hi. The total is 1999 + 1998 + … + 1 = 1999 × 2000 / 2 = 1,999,000 comparisons, which is quadratic.
Exercise
Why does fixed median-of-three give a perfect split on sorted input, and why does that not protect it from every bad input?
Show answer
On sorted input, a[lo] ≤ a[mid] ≤ a[hi], so the rule picks a[mid], which is the true median of the range. Lomuto partitioning leaves the range sorted, so every later round also splits evenly. The rule always samples the same three positions, though. An adversary can build an input that places small values at those positions in every round, so the chosen pivot is always near the minimum. Each partition then discards only a few elements, and the run is quadratic. Sampling the three positions at random removes this weakness.