Sub topic 5
Choosing a Pivot: Random, First Element, and Median-of-Three
This chapter assumes you already know Lomuto partitioning and the in-place iterative quickselect from the previous chapters. You should also be comfortable reading Big-O notation. Here the partitioning and the loop stay the same. Only one line changes: the line that picks the pivot index.
Why the Pivot Matters
Each partition step removes the pivot's side that cannot contain index k. A good pivot lands near the middle of the current range, so about half the range disappears. A bad pivot lands at one end. Then only one element disappears, and the next partition has to scan almost the same range again.
How often bad pivots happen depends on two things: the rule you use to pick the pivot, and the order of the input. The next chapter does the formal running-time analysis. This chapter compares the rules in practice.
Three Common Strategies
| Strategy | How it picks | Cost per step | Weak spot |
|---|---|---|---|
| First element | Always `a[lo]` | Free | Sorted or reverse-sorted input gives O(n²) |
| Median-of-three | Median of `a[lo]`, `a[mid]`, `a[hi]` | Three comparisons | Crafted "killer" inputs can still force O(n²) |
| Random | Uniform index in `[lo, hi]` | One random number | Bad luck only, and it is very unlikely on large inputs |
First element looks harmless, but real data is often already sorted or almost sorted. On sorted input the first element is the minimum of the range, so every partition removes just one element.
Median-of-three samples the two ends and the middle and uses the middle value of the three as the pivot. On sorted input it picks the true median of the range, which is the best possible pivot. It is deterministic, though. An attacker who knows your code can build an input that makes it fail.
Random pivots do not depend on the input order, so no fixed input is bad every time. You get expected linear time on any input, which is the property the complexity chapter proves.
Measuring the Difference
The program below passes the pivot rule to quickselect as a function. It counts element comparisons inside partition, so you can compare the rules on the same sorted input.
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 first_pivot(a, lo, hi):
return lo
def random_pivot(a, lo, hi):
return random.randint(lo, hi)
def median_of_three(a, lo, hi):
mid = (lo + hi) // 2
trio = sorted([(a[lo], lo), (a[mid], mid), (a[hi], hi)])
return trio[1][1] # index of the middle value
def quickselect(a, k, choose):
"""Return (k-th smallest, comparisons). Reorders a in place."""
if not 0 <= k < len(a):
raise IndexError("k out of range")
counter = [0]
lo, hi = 0, len(a) - 1
while lo < hi:
p = partition(a, lo, hi, choose(a, lo, hi), counter)
if k == p:
return a[k], counter[0]
elif k < p:
hi = p - 1
else:
lo = p + 1
return a[lo], counter[0]
n = 2000
k = n // 2
for name, rule in [("first", first_pivot),
("median-of-3", median_of_three),
("random", random_pivot)]:
data = list(range(n)) # already sorted
value, comparisons = quickselect(data, k, rule)
print(f"{name:12} value={value} comparisons={comparisons}")All three rules return 1000. The first-element rule makes exactly 1,500,499 comparisons, which grows quadratically with n. Median-of-three makes about 4,000 because it finds the exact middle of a sorted range each time. The random rule varies between runs but usually stays within a small multiple of n, at a few thousand comparisons. If you double n, the first-element count roughly quadruples and the other two roughly double.
Practical Guidance
- Use a random pivot by default. It adds one random-number call per partition and removes any dependence on input order.
- Median-of-three suits trusted inputs that are often sorted, or code that must be reproducible without seeding a random generator. You can also combine the two: take the median of three randomly chosen positions.
- Avoid first-element and last-element pivots unless you know the input is already shuffled.
- Production code that faces untrusted input often adds a fallback with a worst-case guarantee. Later chapters cover median of medians and introselect.
Exercise
Run quickselect with the first-element pivot rule on a reverse-sorted list list(range(n, 0, -1)) with k = 0. How many partition steps happen, and why? Would median-of-three behave better here?
Show answer
Each step uses the first element, which is the largest value in the current range. The pivot lands at index hi, k = 0 lies to its left, and only one element is removed per step. The run takes about n - 1 partitions and roughly n²/2 comparisons. Median-of-three samples the two ends and the middle of a sorted or reverse-sorted range, so its pivot is near the true median and about half the range is removed each step.
Exercise
Why can an attacker defeat median-of-three but not a random pivot drawn from an unpredictable generator?
Show answer
Median-of-three always looks at the same positions, so someone who knows the rule can place values there so the chosen median is near an extreme every time. A random pivot depends on numbers the attacker cannot predict, so no fixed input forces bad pivots. Every input then gets expected linear time.