Sub topic 10
Median-of-Three Pivot Selection
This chapter assumes you already know the Lomuto partition scheme, the in-place recursive quicksort built on it, and why a fixed last-element pivot turns sorted input into an O(n²) case. Randomized quicksort, covered earlier, avoids that case by chance. Median-of-three avoids it with a cheap, deterministic look at the data.
The idea
A pivot works best when it lands near the middle of the values in the range. Finding the true median would take too long. Instead, look at three elements: the first, the middle, and the last. Then use the median of those three as the pivot.
The sample costs at most three comparisons per partition. It also fixes the most common bad inputs. On sorted or reverse-sorted data, the middle element is the true median, so every split is balanced.
Implementation
The function below orders the three sampled elements in place, so that a[lo] <= a[mid] <= a[hi]. It then moves the median into position hi, where Lomuto expects the pivot. The partition code itself stays the same.
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = lo
for j in range(lo, hi):
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_m3(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = median_of_three_partition(a, lo, hi)
quicksort_m3(a, lo, p - 1)
quicksort_m3(a, p + 1, hi)
data = list(range(5000)) # sorted input: quadratic with a last-element pivot
quicksort_m3(data)
print(data == sorted(data)) # True, with recursion depth about log2(5000)On sorted input, a plain last-element pivot would recurse about 5000 levels deep and hit Python's default recursion limit. With median-of-three, the recursion goes about 13 levels deep.
What it does and does not guarantee
| Property | Fixed last pivot | Median-of-three | Random pivot |
|---|---|---|---|
| Sorted / reverse-sorted input | O(n²) | O(n log n) | O(n log n) expected |
| Deterministic | Yes | Yes | No |
| Adversarial worst case | Easy to build | Possible to build | No fixed bad input |
| Extra cost per partition | None | ≤ 3 comparisons | One RNG call |
The sample also makes splits more balanced on typical data. The expected pivot rank is closer to the middle than a single random pick's, which cuts the average number of comparisons by roughly 5 to 10 percent in practice.
Common mistakes:
- Computing the median but forgetting to swap it into
hi. Lomuto then partitions around the wrong value. - Writing
mid = (lo + hi) // 2aslen(a) // 2. That ignores the subarray bounds during recursion. - Assuming median-of-three helps with many duplicate keys. It does not. Equal keys still need three-way partitioning.
Exercise
For the range [9, 4, 7, 1, 3] (lo = 0, hi = 4), which value does median-of-three choose as the pivot, and what is the array just before lomuto_partition runs?
Show answer
The samples are a[0] = 9, a[2] = 7, and a[4] = 3, so the median is 7. Ordering the samples gives [3, 4, 7, 1, 9]. Swapping a[mid] and a[hi] then gives [3, 4, 9, 1, 7], with pivot 7 at index 4.
Exercise
Why does median-of-three remove the O(n²) behavior on sorted input but still not guarantee O(n log n) in the worst case?
Show answer
On sorted input, the middle sample is the true median, so every split is even. The rule is deterministic, though. An adversary can arrange the values so that each three-element sample has a median near the minimum or maximum of the range. Then the partitions stay unbalanced and the running time is quadratic.