Sub topic 16
Worked example: quicksort
This chapter assumes you know the best, worst, and average case definitions from earlier chapters, the linear search and insertion sort examples, and how recursion works. Here we apply those ideas to quicksort and add one new factor: random choices made by the algorithm itself.
How the cost arises
Quicksort picks a pivot, splits the other elements into those smaller and those larger than the pivot, and sorts each part recursively. For distinct values, each partition step compares every non-pivot element with the pivot once, so a list of size m costs m - 1 comparisons. The total cost depends on how balanced the splits are.
Best and worst case
- Best case: every pivot is the median. The depth is about log2 n and each level costs about n comparisons, so the total is about n log2 n.
- Worst case: every pivot is the smallest or largest element. The costs are (n - 1) + (n - 2) + ... + 1 = n(n - 1)/2.
With a "first element" pivot rule, an already sorted list produces the worst case. That is a common input in practice.
Measuring a randomized pivot
The average case needs an input distribution. Randomizing the pivot avoids that assumption. The expected cost is then taken over the algorithm's own random choices, for any fixed input. This program counts comparisons for a sorted input of 200 values.
import random
def quicksort_comparisons(values, pick_pivot):
if len(values) <= 1:
return 0
pivot = pick_pivot(values)
smaller = [x for x in values if x < pivot]
larger = [x for x in values if x > pivot]
return (len(values) - 1) + quicksort_comparisons(smaller, pick_pivot) \
+ quicksort_comparisons(larger, pick_pivot)
n = 200
items = list(range(n)) # sorted, distinct values
print(quicksort_comparisons(items, lambda a: a[0])) # 19900 = n(n-1)/2
runs = [quicksort_comparisons(items, random.choice) for _ in range(100)]
print(sum(runs) / len(runs)) # about 1560, varies per runThe first-element rule gives exactly n(n - 1)/2 = 19,900. The random rule gives a mean near 1,560. The exact expected count is 2(n + 1)Hn - 4n, where Hn is the harmonic number 1 + 1/2 + ... + 1/n. This grows like 2n ln n, which is about 1.39 n log2 n.
Choosing a case
| Pivot rule | Best case | Worst case | Typical behavior |
|---|---|---|---|
| First element | about n log2 n | n(n - 1)/2, on sorted input | Fine on random order, slow on sorted data |
| Random element | about n log2 n | n(n - 1)/2, with tiny probability | Expected about 1.39 n log2 n on every input |
If you need a hard latency guarantee, rely on the worst case. Quicksort's worst case is quadratic, so a guarantee calls for a different algorithm, such as merge sort or heapsort. For throughput over many sorts, the expected time is the right measure.
Exercise
For a list of 5 distinct values sorted in ascending order, how many comparisons does quicksort make with a first-element pivot? What formula gives it?
Show answer
10 comparisons. Each pivot is the smallest remaining element, so the costs are 4 + 3 + 2 + 1 = 10, which equals n(n - 1)/2 for n = 5.