Sub topic 12
Divide and Conquer: Merge Sort
This chapter assumes you can read Python functions that use lists, slicing, and while loops. It also assumes you are comfortable with the earlier chapters on base cases, the recursive leap of faith, and tree recursion. You will see how a recursive function can split a problem into halves, solve each half, and combine the answers. Merge sort is the standard worked example of this approach.
The Divide-and-Conquer Pattern
Divide and conquer is a way of designing recursive algorithms in three steps:
- Divide: split the input into smaller subproblems of the same kind.
- Conquer: solve each subproblem recursively. Inputs small enough to answer directly are the base case.
- Combine: merge the subproblem answers into an answer for the whole input.
Recursion on lists in an earlier chapter used a different split. Code like items[0] + total(items[1:]) peels off one element at a time, so the chain of calls is as long as the list. Divide and conquer splits the input into parts of roughly equal size instead. Each call makes two recursive calls, which is tree recursion. Unlike naive Fibonacci, though, the two halves never overlap, so no subproblem is solved twice and memoization would not help.
| Approach | Split | Recursion depth for n items | Overlapping subproblems |
|---|---|---|---|
| First element + rest | 1 and n − 1 | n | No |
| Naive Fibonacci | n − 1 and n − 2 | n | Yes, many |
| Divide and conquer (halves) | n/2 and n/2 | about log₂ n | No |
Merge Sort
Merge sort uses the pattern like this:
- Divide: cut the list at its midpoint.
- Conquer: sort each half with merge sort.
- Combine: merge the two sorted halves into one sorted list.
The base case is a list of length 0 or 1, which is already sorted.
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
print(merge_sort([5, 2, 9, 1, 3])) # [1, 2, 3, 5, 9]Apply the leap of faith here. Assume merge_sort(items[:mid]) returns the left half sorted and merge_sort(items[mid:]) returns the right half sorted. The only part you then need to check is the merge loop: given two sorted lists, does it produce one sorted list? You don't need to trace every call to convince yourself the function is correct.
How the Merge Step Works
The merge keeps one index into each sorted half. At each step it compares left[i] with right[j], appends the smaller value, and moves that index forward. When one half runs out, everything left in the other half is already sorted and larger than or equal to everything in merged. The two extend calls append that leftover tail.
Every comparison moves exactly one element into merged, so merging lists with a combined length of n takes O(n) time.
Watching the Splits and Merges
The diagram shows the calls for [5, 2, 9, 1, 3]. The midpoint is len // 2, so a list of 5 splits into 2 and 3 elements. The list of 3 then splits into 1 and 2.
To see the order the call stack actually runs these calls in, add a depth parameter and print on the way in and on the way out:
def merge_sort_traced(items, depth=0):
pad = " " * depth
print(pad + "sort", items)
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort_traced(items[:mid], depth + 1)
right = merge_sort_traced(items[mid:], depth + 1)
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
print(pad + "merged", merged)
return merged
merge_sort_traced([5, 2, 9, 1, 3])The output shows that the left half is fully sorted before the right half starts. Python finishes the first recursive call, with all of its descendants, before it evaluates the second.
sort [5, 2, 9, 1, 3]
sort [5, 2]
sort [5]
sort [2]
merged [2, 5]
sort [9, 1, 3]
sort [9]
sort [1, 3]
sort [1]
sort [3]
merged [1, 3]
merged [1, 3, 9]
merged [1, 2, 3, 5, 9]Cost: Time, Depth, and Memory
Each level of the call tree merges a combined total of n elements, so each level costs O(n). Halving the input at each level gives about log₂ n levels. The total time is O(n log n). This holds in the best, average, and worst case, because the splits never depend on the data. A later chapter turns this argument into the recurrence T(n) = 2T(n/2) + O(n) and solves it formally.
The recursion depth is only about log₂ n. Sorting a million items needs roughly 20 nested frames, far below CPython's default limit of about 1000. This is a practical advantage of balanced splitting over first-plus-rest recursion, which needs one frame per element.
Memory is the trade-off. This version builds new lists through slicing and through merged, so it uses O(n) extra space at any one time, plus the copying work. Production implementations often pass index bounds instead of slicing and reuse a single buffer. In-place sorts such as heapsort avoid the extra memory but give up other properties.
Common Errors
A Base Case That Misses Length 1
If the base case is only if not items: return items, a one-element list gives mid = 0. Then items[:0] is empty and items[0:] is the same one-element list. The call recurses on an input that never gets smaller, which ends in RecursionError. Every recursive call must receive a strictly smaller input. The len(items) <= 1 check guarantees that, because any list of length 2 or more splits into two non-empty parts.
Forgetting the Leftover Tail
If you drop the two extend lines, elements are lost whenever one half runs out first. That happens in nearly every merge. A quick check for this bug is len(result) == len(input).
Using `<` Instead of `<=`
With <, equal elements are taken from the right half first. The output is still sorted, but the sort is no longer stable. A stable sort keeps equal elements in their original relative order. Stability matters when you sort records by one key after already sorting them by another.
When to Reach for Divide and Conquer
Divide and conquer fits when three conditions hold:
- The problem splits into independent subproblems of the same kind.
- The subproblem answers can be combined cheaply, ideally in linear time.
- Balanced splits are possible, so the depth stays logarithmic.
Binary search, quicksort, closest pair of points, and Karatsuba multiplication all follow this outline. When subproblems overlap, as they do in Fibonacci, use memoization or dynamic programming instead.
Exercise
Change merge_sort to also return the number of inversions in the list, meaning pairs (i, j) with i < j and items[i] > items[j]. Which line of the merge loop is the right place to count them, and how many should you add there?
Show answer
Count in the else branch, where right[j] is taken before left[i]. right[j] is smaller than left[i] and every element after it in left, so add len(left) - i. Return a tuple (sorted_list, count) and add the counts from both recursive calls to the count from the merge. For [5, 2, 9, 1, 3] the total is 5.
Exercise
What is the maximum recursion depth (counting the top call as depth 1) when merge_sort sorts a list of 1,000,000 items, and why can it not hit CPython's default recursion limit?
Show answer
The length halves at each level, so the depth is about ceil(log2(1,000,000)) + 1 = 21. That is far below the default limit of about 1000, because depth grows logarithmically rather than linearly with n.
Exercise
A student replaces mid = len(items) // 2 with mid = 1. Is the result still correct, and what happens to the running time and depth?
Show answer
The sort is still correct, because each call still receives a smaller non-empty part. But the split is now 1 and n − 1, so the depth becomes about n and the time becomes O(n²), the same as insertion sort. Lists longer than about 1000 items will also raise RecursionError.