Sub topic 9
Quicksort: Doing the Work Before Recursing
This chapter assumes you already know the merge sort chapter, the recurrence T(n) = 2T(n/2) + O(n), the master theorem, and how to trace recursive Python functions. You should also be comfortable swapping list elements in place.
Where the Work Happens
Merge sort makes the split trivial and puts the hard work in the combine step. It cuts the list at the middle index, recurses, and then merges in linear time. Quicksort reverses this. Its divide step is a partition: it picks a pivot value and rearranges the list so that everything smaller than the pivot comes before it and everything larger comes after it. After partitioning, the pivot is already in its final sorted position. The two sides are sorted recursively, and the combine step does nothing, because the sorted pieces are already in the right order next to each other.
| Step | Merge sort | Quicksort |
|---|---|---|
| Divide | Split at middle index, O(1) | Partition around pivot, O(n) |
| Conquer | Sort both halves | Sort both sides of pivot |
| Combine | Merge, O(n) | Nothing |
| Subproblem sizes | Always balanced | Depend on the pivot |
| Extra memory | O(n) for merging | O(log n) stack if done carefully |
| Worst case | O(n log n) | O(n²) |
The last two rows explain why both algorithms are still in use. Quicksort sorts in place and has tight inner loops. Merge sort guarantees balanced splits.
An In-Place Implementation
The version below uses the Lomuto partition scheme with a random pivot. Lomuto's scheme scans left to right and keeps an index i marking the end of the "less than pivot" region.
import random
def partition(a, lo, hi):
# Partition a[lo..hi] (inclusive) around a random pivot.
# Returns the pivot's final index.
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r] # move pivot to the end
pivot = a[hi]
i = lo # a[lo..i-1] < pivot
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] # place pivot between the regions
return i
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi: # 0 or 1 elements: already sorted
return
p = partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
data = [5, 2, 9, 1, 5, 6]
quicksort(data)
print(data) # [1, 2, 5, 5, 6, 9]The loop maintains an invariant. At the start of each iteration, a[lo..i-1] holds elements less than the pivot and a[i..j-1] holds elements greater than or equal to it. When the loop ends, swapping the pivot into index i puts it between the two regions. The correctness argument by induction works as before. Each recursive call gets a range strictly smaller than hi - lo + 1 because the pivot is excluded, so recursion terminates. If both sides come back sorted, the whole range is sorted, because every element on the left is less than every element on the right.
How the Pivot Decides the Running Time
Partitioning costs Θ(n), but the sizes of the two subproblems depend on where the pivot lands.
Best and balanced cases
If the pivot is always the median, the recurrence is T(n) = 2T(n/2) + Θ(n). By case 2 of the master theorem this gives Θ(n log n). An unbalanced but constant-ratio split, such as 1/10 against 9/10, also gives Θ(n log n). The recursion tree then has depth log base 10/9 of n, which is still logarithmic, and each level does at most n work.
Worst case
If the pivot is always the smallest or largest element, one side is empty and the other has n − 1 elements:
T(n) = T(n − 1) + Θ(n) = Θ(n + (n−1) + ... + 1) = Θ(n²)
The master theorem does not apply here, because the subproblem shrinks by subtracting 1 instead of dividing by a constant. Summing the recursion tree, which is a single path, gives the quadratic bound.
Expected case with a random pivot
With a uniformly random pivot, the expected number of comparisons is about 2n ln n, roughly 1.39 n log₂ n. A short way to see why: call a pivot "good" if it falls in the middle half of the values. That happens with probability 1/2. A good pivot leaves at most 3n/4 elements on either side. So on average every two levels shrink each element's subproblem by a constant factor, and each element takes part in O(log n) partitions in expectation. The total is O(n log n).
The expectation is taken over the algorithm's own random choices, not over the input. No input is bad for randomized quicksort. Some runs are just unlucky, and the probability of a run much slower than n log n is tiny.
Pivot Selection Strategies
| Strategy | Cost | Weakness |
|---|---|---|
| First or last element | O(1) | Θ(n²) on already sorted or reverse-sorted input |
| Random element | O(1) plus a random number | Expected O(n log n), small constant overhead |
| Median of three (first, middle, last) | O(1) | Deterministic, so specially built inputs can still force Θ(n²) |
| Median of medians | O(n) | Guarantees balance, but the constant is too high for sorting in practice |
Sorted input is common in real data, which is why a fixed first-element pivot is a real hazard. Median of medians is covered in the selection chapter. Production libraries usually rely on median of three or random pivots, plus a fallback that switches to heapsort when the recursion gets too deep. That hybrid is called introsort.
Duplicates and Three-Way Partitioning
Look at what Lomuto does with [7, 7, 7, 7]. The test a[j] < pivot never succeeds, so the pivot ends at lo and the right side holds n − 1 elements. Each level removes one element, and the running time is Θ(n²) no matter how the pivot is chosen. A random pivot does not help.
The fix is to split the range into three regions: less than, equal to, and greater than the pivot. The equal region is never recursed on.
import random
def quicksort3(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
pivot = a[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi
# a[lo..lt-1] < pivot, a[lt..i-1] == pivot, a[gt+1..hi] > pivot
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1 # do not advance i: the swapped-in value is unexamined
else:
i += 1
quicksort3(a, lo, lt - 1)
quicksort3(a, gt + 1, hi)
data = [3, 1, 3, 3, 2, 3, 1, 3]
quicksort3(data)
print(data) # [1, 1, 2, 3, 3, 3, 3, 3]On an all-equal list, one partition pass puts everything in the middle region and the sort finishes in Θ(n).
Common Errors and Gotchas
- Stability. Quicksort is not stable. Equal elements can change their relative order during swaps. If you need stability, use merge sort.
- Stack depth. Worst-case recursion depth is n, and Python's default recursion limit of about 1000 will be exceeded. Recursing on the smaller side and looping on the larger one keeps the depth at O(log n). The practical concerns chapter covers this.
- Infinite loops in Hoare partitioning. Hoare's scheme, which scans from both ends, does fewer swaps. It returns a split index rather than the pivot's final position, though, so the recursive calls must be
(lo, p)and(p + 1, hi). Mixing these bounds with Lomuto's leads to non-termination. - Comparing with
<=. Changing the Lomuto test toa[j] <= pivotmoves the problem with duplicates to the other side instead of fixing it.
Exercise
Suppose quicksort always picks the last element as the pivot and runs on the already sorted list [1, 2, 3, ..., n]. Write the recurrence and give the running time.
Show answer
Each pivot is the maximum of its range, so the left side has n − 1 elements and the right side is empty. T(n) = T(n − 1) + Θ(n), which sums to Θ(n²). The recursion depth is also n, so a large n will overflow Python's recursion limit.
Exercise
A list of one million elements contains only the values 0 and 1. Compare the running time of the Lomuto quicksort with a random pivot to quicksort3.
Show answer
With Lomuto, every element equal to the pivot goes to the right side, so once a range holds a single distinct value, each partition removes only one element. That part costs Θ(n²). quicksort3 puts all copies of the pivot in the middle region and never recurses on them. After at most two partition levels only empty ranges are left, so it runs in Θ(n).
Exercise
Why does quicksort need no combine step, while merge sort needs a linear-time merge?
Show answer
Partitioning ensures that every element left of the pivot is smaller than every element right of it before the recursive calls run. Once both sides are sorted, the concatenation is already sorted. Merge sort splits by position, not value, so its sorted halves can interleave and have to be merged.