Sub topic 4
Putting It Together: Recursive Quicksort
This chapter assumes you can read Python, that you understand how recursive calls use the call stack, and that you have the Lomuto partition function from the previous chapter. Here we take that partition step and build a complete, in-place sorting algorithm on top of it. Along the way, you will trace a real run, argue that the algorithm is correct, and look at the mistakes people most often make when they write it from memory.
The Shape of the Algorithm
Quicksort on a range a[lo..hi] (both ends inclusive) has three steps:
- Base case. If the range has zero or one element, it is already sorted. Return.
- Partition. Rearrange the range so the pivot lands at some index
p. Every element to its left is smaller than the pivot, and every element to its right is greater than or equal to it. - Recurse. Sort
a[lo..p-1]anda[p+1..hi]separately.
There is no "combine" step. Merge sort does its real work after the recursive calls return, when it merges. Quicksort does its real work before the recursive calls, when it partitions. Once both sides are sorted, the whole range is sorted, because the partition already put every element on the correct side of the pivot.
The Implementation
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 quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
data = [5, 3, 8, 1, 9, 2]
quicksort(data)
print(data) # [1, 2, 3, 5, 8, 9]A few design decisions are packed into these lines.
- Inclusive bounds.
loandhiboth name valid indices. This matches Lomuto's use ofa[hi]as the pivot. The top-level call therefore useshi = len(a) - 1, notlen(a). - A default of
Noneforhi. Callers can writequicksort(data)without knowing the index convention. A default likehi=len(a) - 1would not work, because Python evaluates defaults once, when the function is defined, andadoes not exist then. lo < hias the guard. This single test covers both base cases. A one-element range haslo == hi. An empty range haslo > hi, which happens when the pivot lands at either end of the range, for examplep - 1 < lowhenp == lo.- No return value. The function sorts the list it receives. It follows the same convention as Python's
list.sort(), which returnsNone.
Why the Bounds Are `p - 1` and `p + 1`
After Lomuto partitioning, a[p] holds the pivot at its final sorted position. No later step will ever move it. So both recursive calls exclude index p.
Excluding p also guarantees termination. Each recursive call covers at most hi - lo elements, which is one fewer than the parent range. Sizes strictly decrease, so the recursion must reach the base case. If p were included in one side, a pivot that happened to be the largest element would give p == hi. The call quicksort(a, lo, p) would then repeat the exact same range forever.
Tracing a Run
The version below prints each partition and each base case, indented by recursion depth.
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 quicksort_traced(a, lo=0, hi=None, depth=0):
if hi is None:
hi = len(a) - 1
indent = " " * depth
if lo >= hi:
print(f"{indent}base case [{lo}..{hi}]")
return
p = lomuto_partition(a, lo, hi)
print(f"{indent}partition [{lo}..{hi}] -> p={p}, a={a}")
quicksort_traced(a, lo, p - 1, depth + 1)
quicksort_traced(a, p + 1, hi, depth + 1)
quicksort_traced([5, 3, 8, 1, 9, 2])Output:
partition [0..5] -> p=1, a=[1, 2, 8, 5, 9, 3]
base case [0..0]
partition [2..5] -> p=2, a=[1, 2, 3, 5, 9, 8]
base case [2..1]
partition [3..5] -> p=4, a=[1, 2, 3, 5, 8, 9]
base case [3..3]
base case [5..5]Read it step by step:
- The first pivot is
2. Only1is smaller, so2lands at index 1. The left side[0..0]holds one element. The right side[2..5]holds four. - In
[2..5]the pivot is3, and nothing in the range is smaller. The pivot lands at index 2, which leaves an empty left range[2..1]. - In
[3..5]the pivot is8. It lands at index 4, and each side then holds a single element.
The recursion tree for this run looks like this:
The tree is lopsided. Two of the three pivots were near the minimum of their range, so each partition removed little more than the pivot. A balanced tree would be about log₂ 6 ≈ 2.6 levels deep. This one has three partition levels plus a level of base cases. On six elements that does not matter. The shape of this tree, though, is what decides how fast quicksort runs, and the next chapters analyze it directly.
Why It Is Correct
You can prove quicksort correct by strong induction on the size of the range, n = hi − lo + 1.
- Base: if n ≤ 1, the range is trivially sorted and the function does nothing.
- Step: assume quicksort correctly sorts every range smaller than n. Partition places the pivot
xatp, witha[lo..p-1] < x ≤ a[p+1..hi]. Both sub-ranges have fewer than n elements, so by the hypothesis the recursive calls sort them. Sorting a side only reorders elements inside that side, so the partition property still holds afterward. A sorted left part, thenx, then a sorted right part, with everything on the left belowxand everything on the right at leastx, is a sorted range.
The proof uses only two facts about the partition step: the pivot ends at p, and the sides are correctly separated. Any partition function that guarantees both can be used with this recursion unchanged.
Testing Against a Reference
It is easy to introduce off-by-one bugs, and small hand-picked examples often miss them. A randomized test against Python's built-in sorted catches most of them in seconds. Run this block in the same session as the implementation block above.
import random
def check(trials=2000):
for _ in range(trials):
n = random.randint(0, 12)
xs = [random.randint(0, 5) for _ in range(n)]
expected = sorted(xs)
actual = xs[:]
quicksort(actual)
assert actual == expected, (xs, actual)
print("all tests passed")
check()The small value range, 0 to 5, matters. It forces many duplicate keys, and duplicates are where partition bugs usually hide. Lengths 0 and 1 also exercise the base cases directly.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `quicksort(a, 0, len(a))` | `IndexError` on `a[hi]` | Use `len(a) - 1`, or rely on the `None` default |
| Recursing on `lo..p` with Lomuto | `RecursionError` when the pivot is the maximum | Exclude the pivot: `lo..p-1` |
| `data = quicksort(data)` | `data` becomes `None` | Call `quicksort(data)` and keep using `data` |
| Guard written as `lo != hi` | Recurses forever on empty ranges where `lo > hi` | Use `lo < hi` |
| Partitioning `a[0..len-1]` instead of `a[lo..hi]` inside recursion | Wrong results or out-of-place swaps | Pass `lo` and `hi` through to the partition |
| Sorting a copy, e.g. `quicksort(a[:])` | Original list unchanged | Pass the list itself |
Exercise
Using the Lomuto quicksort in this chapter, how many calls to lomuto_partition are made when sorting [4, 4, 4, 4]? Explain what happens at each level.
Show answer
Three. The pivot is a[hi] = 4, and no element is strictly less than 4, so every partition places the pivot at p = lo. The first call on [0..3] gives p = 0, an empty left side, and a right side [1..3]. Then [1..3] gives p = 1, and [2..3] gives p = 2. The last right side, [3..3], is a base case. Each partition removes only the pivot, which is why equal keys are a problem case. A later chapter returns to this.
Exercise
A colleague changes the recursive calls to quicksort(a, lo, p) and quicksort(a, p + 1, hi) but keeps lomuto_partition. Give a three-element input that makes this version recurse forever, and explain why.
Show answer
Any input whose last element is the maximum works, for example [1, 2, 3]. The pivot 3 is larger than every other element, so it stays at p = hi = 2. The left call is then quicksort(a, 0, 2), the same range as before, and it repeats without end until Python raises RecursionError.
Exercise
Modify quicksort so it sorts in descending order by changing exactly one character in lomuto_partition. Which character, and why does the recursion not need to change?
Show answer
Change a[j] < pivot to a[j] > pivot. Partition then puts larger elements left of the pivot and smaller-or-equal elements right of it. The pivot still ends at its final position p, and the correctness proof only depends on that fact and on the two sides being separated, so the recursion bounds lo..p-1 and p+1..hi stay the same.