Sub topic 10
Median-of-Three Pivot Selection
This chapter assumes you have worked through the Lomuto partition scheme, the recursive quicksort built on it, and the earlier analysis showing that a fixed last-element pivot degrades to O(n²) on sorted input. You should also be comfortable reading Python that swaps elements in place.
Randomized pivots, from the previous chapter, protect against bad inputs by making the pivot unpredictable. Median-of-three takes a deterministic approach. It looks at a few elements, makes an informed guess about where the middle of the range is, and uses that guess as the pivot. Many classic library sorts use it because it is cheap, needs no random number generator, and fixes the most common bad cases in real data.
The Idea
A pivot is good when it lands near the middle of the values in the range, so that both partitions come out about the same size. The true median would be the perfect pivot, but finding it costs more than it saves. Median-of-three estimates it from a sample of three elements:
- Take the first element
a[lo], the middle elementa[mid], and the last elementa[hi]. - Find the median of those three values.
- Use that value as the pivot.
By definition, the median of three values is never the smallest or the largest of them. So the chosen pivot is guaranteed to have at least one element in the range that is no larger than it and at least one that is no smaller. That guarantee looks small, but it removes the worst split of all, where one side gets everything except the pivot. That split is exactly what happens on sorted input when the pivot is always the last element.
Implementing It on Top of Lomuto
The Lomuto scheme expects its pivot at a[hi]. The simplest way to add median-of-three is to work out which of the three candidates is the median, move it to hi, and call the existing partition function unchanged.
Three compare-and-swap steps put the three candidates in order:
- If
a[mid] < a[lo], swap them. Nowa[lo] <= a[mid]. - If
a[hi] < a[lo], swap them. Nowa[lo]is the smallest of the three. - If
a[hi] < a[mid], swap them. Nowa[lo] <= a[mid] <= a[hi].
After these steps the median is at mid. One more swap moves it to hi.
The script below implements this and measures the difference. It counts the comparisons made inside the partition loop, sorts the same already-sorted array with both pivot strategies, and checks that both results are correct.
comparisons = 0
def lomuto_partition(a, lo, hi):
global comparisons
pivot = a[hi]
i = lo
for j in range(lo, hi):
comparisons += 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 median_of_three_partition(a, lo, hi):
mid = (lo + hi) // 2
if a[mid] < a[lo]:
a[lo], a[mid] = a[mid], a[lo]
if a[hi] < a[lo]:
a[lo], a[hi] = a[hi], a[lo]
if a[hi] < a[mid]:
a[mid], a[hi] = a[hi], a[mid]
# Now a[lo] <= a[mid] <= a[hi]; move the median into the pivot slot.
a[mid], a[hi] = a[hi], a[mid]
return lomuto_partition(a, lo, hi)
def quicksort(a, lo, hi, partition):
if lo < hi:
p = partition(a, lo, hi)
quicksort(a, lo, p - 1, partition)
quicksort(a, p + 1, hi, partition)
def run(name, partition, n=500):
global comparisons
comparisons = 0
data = list(range(n)) # already sorted
quicksort(data, 0, n - 1, partition)
assert data == list(range(n))
print(f"{name:>16}: {comparisons} comparisons")
run("last element", lomuto_partition)
run("median of three", median_of_three_partition)The last-element version makes exactly n(n − 1)/2 = 124,750 comparisons on 500 sorted elements, and its recursion goes 500 levels deep. The median-of-three version makes a few thousand comparisons, more than 20 times fewer, and its recursion depth is about log₂ 500 ≈ 9. The gap grows with n. At n = 2,000 the last-element version also exceeds Python's default recursion limit of 1,000 and crashes.
Why sorted input now splits evenly
On a sorted range, the three candidates are already in order, so the median is the true middle element. After that element is swapped to hi, the largest element sits at mid. Lomuto's loop leaves the left half in place. The final pivot swap then moves the largest element back to hi, so both subranges stay sorted. Each recursive call therefore sees sorted input again and splits it in half again. The same reasoning covers input that is almost sorted, which is common in practice: data that has been appended to, or records sorted by timestamp.
What It Buys on Random Input
Median-of-three also helps when the input is not adversarial. A single random element is just as likely to land near the edges of the range as near the center. The median of three random elements clusters toward the center, so splits are more balanced on average.
The expected comparison counts for a random permutation, using the standard textbook results, are:
| Pivot strategy | Expected comparisons | Approx. in terms of n log₂ n |
|---|---|---|
| Random or fixed element (on random input) | 2n ln n | 1.39 n log₂ n |
| Median of three random elements | (12/7) n ln n | 1.19 n log₂ n |
That is about 14% fewer comparisons. You pay for it with up to three extra comparisons and a few swaps per partition call. Partition calls on large ranges do linear work, so this extra constant cost hardly registers.
Gotchas and Common Errors
It is deterministic, so it can be defeated
Median-of-three only samples three fixed positions. An input built so that two of those three positions hold small values at every level of recursion makes each split peel off only a couple of elements, and the running time returns to O(n²). David Musser described such "median-of-3 killer" sequences in his 1997 introsort paper. Douglas McIlroy's 1999 paper "A Killer Adversary for Quicksort" showed how to generate bad inputs against almost any deterministic pivot rule. When inputs might come from an attacker, median-of-three alone is not enough. You need randomization or a worst-case fallback, which the introsort chapter covers.
It does not help with many duplicates
If every element is equal, the median of any three is that same value, and Lomuto still puts everything on one side. Pivot choice cannot fix this. Three-way partitioning, covered in a later chapter, is the fix.
Index and overflow details
- Compute
midfromloandhi, not fromlen(a). The recursion works on subranges. - In languages with fixed-width integers,
(lo + hi) / 2can overflow on very large arrays. Writelo + (hi - lo) / 2. Python integers do not overflow, so the code above is safe as written. - On a range of two elements,
mid == lo. The code still works because the compare-and-swap steps handle repeated indices correctly, but check this edge case if you change the code.
Variations
Median-of-three with random sampling
Choosing three random positions instead of lo, mid, and hi combines the balance gain of sampling with the unpredictability of randomization. Adversarial inputs then no longer work.
Sentinels for a faster inner loop
After the three-element ordering step, a[lo] <= pivot <= a[hi]. Some implementations, usually Hoare-style ones, use these two known values as sentinels: the scanning loops are guaranteed to stop at them, so the explicit bounds checks can be dropped. Saving a branch in the innermost loop is a large part of why median-of-three became standard in hand-tuned sorts.
Ninther for large arrays
Jon Bentley and Douglas McIlroy's "Engineering a Sort Function" (1993) uses Tukey's ninther on large ranges. It takes the median of three medians-of-three, sampled from nine spread-out positions. This gives a better estimate of the true median for little extra cost, and their qsort used it for ranges larger than about 40 elements.
| Strategy | Extra cost per partition | Fixes sorted input | Resists adversaries | Fixes duplicates |
|---|---|---|---|---|
| Last element | none | no | no | no |
| Random element | one RNG call | yes (expected) | yes | no |
| Median of three (fixed positions) | ≤ 3 comparisons | yes | no | no |
| Median of three random | 3 RNG calls + ≤ 3 comparisons | yes | yes | no |
| Ninther | ≤ 12 comparisons | yes | no | no |
Exercises
Exercise
Trace medianofthree_partition on a = [9, 4, 7, 1, 3] with lo = 0 and hi = 4. Give the array after the three compare-and-swap steps, after moving the median to hi, and after partitioning, and state the returned index.
Show answer
mid = 2, so the candidates are a[0]=9, a[2]=7, a[4]=3. Step 1: 7 < 9, swap indices 0 and 2, giving [7, 4, 9, 1, 3]. Step 2: 3 < 7, swap indices 0 and 4, giving [3, 4, 9, 1, 7]. Step 3: a[4]=7 < a[2]=9, swap, giving [3, 4, 7, 1, 9]. The median 7 is at mid. Swap indices 2 and 4: [3, 4, 9, 1, 7]. Lomuto with pivot 7: j=0 (3<7) i becomes 1; j=1 (4<7) i becomes 2; j=2 (9) no move; j=3 (1<7) swap a[2] and a[3], giving [3, 4, 1, 9, 7], i becomes 3. The final swap of a[3] and a[4] gives [3, 4, 1, 7, 9]. The returned index is 3.
Exercise
Your service sorts lists of user IDs that are usually already sorted, but sometimes a client uploads its own list. A colleague proposes median-of-three on lo, mid, hi as the only safeguard. Is that sufficient? What would you change?
Show answer
It handles the common sorted and nearly sorted case well, but it is not sufficient for client-supplied lists, because a client could submit a median-of-3 killer sequence and force O(n²) time, which is a denial-of-service risk. Sample the three candidates at random positions, or keep median-of-three and add a worst-case fallback such as introsort's switch to heapsort when the recursion gets too deep. If the lists can hold many repeated IDs, also use three-way partitioning.