Sub topic 9
Quicksort: Doing the Work Before Recursing
This chapter assumes you know merge sort from the previous chapter, can trace recursive functions, and can read recurrences such as T(n) = 2T(n/2) + O(n).
Merge sort splits the list without looking at it and does its real work in the combine step. Quicksort reverses this. It does its real work in the divide step, called partitioning, so the combine step has nothing left to do.
The Three Steps
- Divide: choose a pivot and rearrange the array so that smaller elements come before it and the rest come after it. The pivot is now in its final position.
- Conquer: recursively sort the part to the left of the pivot and the part to the right.
- Combine: nothing. Both parts are already in place, so the whole range is sorted.
An In-Place Implementation
The version below uses Lomuto partitioning with a random pivot. It sorts the list in place, so it needs no extra arrays.
import random
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
p = partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
def partition(a, lo, hi):
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
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
nums = [5, 2, 9, 1, 5, 6]
quicksort(nums)
print(nums) # [1, 2, 5, 5, 6, 9]Everything in a[lo:i] is less than the pivot. When the loop ends, the pivot is swapped into index i, which is its final position.
Why Pivot Choice Decides the Running Time
Partitioning costs O(n). The running time depends on how evenly the pivot splits the range.
| Split quality | Recurrence | Running time |
|---|---|---|
| Even halves (best) | T(n) = 2T(n/2) + O(n) | O(n log n) |
| Constant fraction, e.g. 1:9 | T(n) = T(n/10) + T(9n/10) + O(n) | O(n log n) |
| One side empty (worst) | T(n) = T(n − 1) + O(n) | O(n²) |
Even a lopsided split like 1:9 keeps the recursion depth at O(log n). The worst case only happens when the pivot is the smallest or largest element at almost every level.
Common Errors
- Off-by-one recursion: recursing on
pinstead ofp - 1orp + 1puts the pivot back into a subproblem. When the pivot ends up at the edge of the range, the subproblem never shrinks and the recursion does not terminate. - Many duplicates: Lomuto sends every element equal to the pivot to the right side. A list of identical values then degrades to O(n²). Three-way partitioning, which groups the elements less than, equal to, and greater than the pivot, fixes this.
- Assuming stability: quicksort can reorder equal elements. Use merge sort when the original order of equal elements must be kept.
Exercise
Quicksort always picks the last element as its pivot and runs on [1, 2, 3, 4, 5]. What are the sizes of the two sides after each partition, and what recurrence describes the running time?
Show answer
The pivot is always the largest element, so the left side has n − 1 elements and the right side is empty: sizes 4 and 0, then 3 and 0, then 2 and 0, then 1 and 0. The recurrence is T(n) = T(n − 1) + O(n), which solves to O(n²).
Exercise
Why does quicksort need no combine step, while merge sort does?
Show answer
Partitioning puts every element on the correct side of the pivot and the pivot in its final position before recursion. Once both sides are sorted in place, the whole range is sorted. Merge sort splits without comparing elements, so it has to merge afterwards.