Show contents
Chapter 2 of 7 · 20 min
Recursion and merge sort
By the end of this chapter, you'll be able to
- Write a recursive function with a base case
- Follow the execution of a recursion through the call stack
- Program merge sort and count its comparisons
- Compare an O(n²) sort with an O(n log n) sort
A function that calls itself
A recursive function solves a problem by calling itself on a smaller version of the same problem. It always has two parts:
- a base case, simple enough to be solved directly;
- a recursive case, which reduces to the same problem, smaller.
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
def power(base, n):
if n == 0:
return 1
return base * power(base, n - 1)
print(total([4, 8, 15, 16, 23, 42]), power(2, 10))
108 1024
The sum of a list is its first item plus the sum of the rest; the sum of an empty list is 0. Each call waits for the result of the next one: Python stacks them on the call stack, then resolves them on the way back up.
Divide and conquer: merge sort
Merge sort applies the same idea to sorting:
- split the list into two halves;
- sort each half, recursively;
- merge the two sorted halves, taking each time the smaller of the two first items.
A list of 0 or 1 item is already sorted: that is the base case.
comparisons = 0
def merge(left, right):
global comparisons
result, i, j = [], 0, 0
while i < len(left) and j < len(right):
comparisons += 1
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]
def merge_sort(items):
if len(items) <= 1:
return items
middle = len(items) // 2
return merge(merge_sort(items[:middle]), merge_sort(items[middle:]))
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
print(comparisons, "comparisons")
[3, 9, 10, 27, 38, 43, 82]
13 comparisons
global comparisons lets merge change the counter defined outside the function. When one of the two halves runs out, the rest of the other is already sorted: it is appended as is.
We merge the two sorted halves by comparing their first items.
Text description of the animation
- We start from a list of 4 items in disorder.
- We cut it in two, then each half in two again.
- One-item lists are sorted by definition: the recursion stops.
- We merge two by two: 1 comparison per pair.
- We merge the two sorted halves by comparing their first items.
Why O(n log n)?
At each level of splitting, the merges of all the sublists cost at most n comparisons in total. And there are about log₂(n) levels, since we halve each time. Total: in the order of n × log₂(n). Let's compare with selection sort, which looks for the minimum of what is left at each turn:
import random
def count_selection(items):
items, comparisons = items[:], 0
for i in range(len(items)):
smallest = i
for j in range(i + 1, len(items)):
comparisons += 1
if items[j] < items[smallest]:
smallest = j
items[i], items[smallest] = items[smallest], items[i]
return comparisons
def count_merge(items):
if len(items) <= 1:
return items, 0
m = len(items) // 2
(l, cl), (r, cr) = count_merge(items[:m]), count_merge(items[m:])
result, i, j, c = [], 0, 0, cl + cr
while i < len(l) and j < len(r):
c += 1
if l[i] <= r[j]:
result.append(l[i]); i += 1
else:
result.append(r[j]); j += 1
return result + l[i:] + r[j:], c
random.seed(0)
for n in (100, 1000, 4000):
data = [random.randint(0, 10**6) for _ in range(n)]
print(f"n = {n:>4}: selection {count_selection(data):>9} merge {count_merge(data)[1]:>6}")
n = 100: selection 4950 merge 542
n = 1000: selection 499500 merge 8690
n = 4000: selection 7998000 merge 42808
When n is multiplied by 4, selection sort makes 16 times more comparisons, merge sort barely 5 times more. In practice, use sorted() or list.sort(): Python uses Timsort, an O(n log n) sort that combines merging and insertion, and is particularly fast on partly sorted data.
Mini-lab: recursion step by stepPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: recursive binary search
Rewrite the binary search of the previous chapter in recursive form: search(items, target, start, end) returns the target's position or -1. Test it on [3, 8, 12, 17, 23, 31, 40, 52] with 23, 3, 52 and 20.
Hint 1
start > end, the area is empty, the target is missing.Hint 2
search again on the left or right half.Show the solution and common mistakes
def search(items, target, start, end):
if start > end:
return -1
middle = (start + end) // 2
if items[middle] == target:
return middle
if items[middle] < target:
return search(items, target, middle + 1, end)
return search(items, target, start, middle - 1)
numbers = [3, 8, 12, 17, 23, 31, 40, 52]
print([search(numbers, t, 0, len(numbers) - 1) for t in (23, 3, 52, 20)])
[4, 0, 7, -1]
Each call works on an area half as large: the recursion depth is about log₂(n), around twenty calls for a million items. No risk of reaching Python's limit.
Common mistakes:
- Calling
search(items, target, middle, end)instead ofmiddle + 1: when the area has two cells, the middle no longer changes and the recursion never stops. - Forgetting the
returnin front of the recursive call: the result is computed, but the function returnsNone.
Summary
- 1A recursive function has a base case and a recursive case that moves towards the base case.
- 2Pending calls pile up on the call stack; too deep, it causes a RecursionError.
- 3Merge sort splits the list, sorts each half and merges: O(n log n).
- 4Selection sort compares each item with the rest: O(n²).
- 5In practice, sorted() and list.sort() use Timsort, in O(n log n).
Your progress is saved on this device. Create a free account to keep your progress on all your devices.