Sub topic 3
Splitting Until One Element Remains
Merge sort has two halves of its own: a splitting phase and a merging phase. The previous chapter built the merge. This chapter covers the splitting: how the recursion cuts a list into pieces, when it stops, how deep it goes, and the off-by-one mistakes that make it loop forever or lose elements. The next chapter connects splitting and merging into the full algorithm.
This chapter assumes you can write recursive functions in Python, understand how the call stack grows and shrinks, know list slicing and indexing, and can read Big-O notation.
What the Splitting Phase Has to Guarantee
The splitting phase has three jobs:
- Make progress. Every recursive call must work on a strictly smaller piece than its parent. Otherwise the recursion never ends.
- Lose nothing and duplicate nothing. The two pieces together must contain exactly the parent's elements, each one once.
- Stop at a piece that is already sorted. That piece is the base case, a problem small enough to answer without more recursion.
A list with zero or one element is sorted by definition, so len(items) <= 1 is the natural base case. Everything larger gets cut in two.
Watching the Splits Happen
The function below does only the splitting. It prints each piece, indented by recursion depth, and it never merges anything.
def show_splits(items, depth=0):
print(" " * depth + str(items))
if len(items) <= 1:
return
mid = len(items) // 2
show_splits(items[:mid], depth + 1)
show_splits(items[mid:], depth + 1)
show_splits([38, 27, 43, 3, 9, 82, 10])Output:
[38, 27, 43, 3, 9, 82, 10]
[38, 27, 43]
[38]
[27, 43]
[27]
[43]
[3, 9, 82, 10]
[3, 9]
[3]
[9]
[82, 10]
[82]
[10]The list has 7 elements, so mid = 7 // 2 = 3. Floor division puts the smaller half on the left: 3 elements go left and 4 go right. With an odd length the halves differ by exactly one, and the tree stays balanced.
The order of the calls
The printed output follows a depth-first, left-to-right walk of the tree. Python finishes the whole left subtree [38, 27, 43] before it touches [3, 9, 82, 10]. So the call stack never holds the whole tree. It only holds the path from the root to the current node. When the walk reaches [27], the stack holds four frames: the root, [38, 27, 43], [27, 43], and [27]. The longest possible path is the tree's height plus one, which is why recursion depth matters more here than the total number of calls.
Splitting by Index Instead of by Slice
Slicing with items[:mid] copies elements. Copying is simple, but each level of the tree copies all n elements again. Production implementations usually pass index bounds into a single shared array instead. The convention that causes the fewest bugs is the half-open range [lo, hi): lo is included and hi is not. In this convention the range holds hi - lo elements, and splitting at mid gives [lo, mid) and [mid, hi) with no gaps and no overlap.
The function below splits by index and reports three numbers for a list of size n: the total number of calls, the number of single-element leaves, and the maximum depth.
import math
def count_calls(lo, hi, depth=0):
"""Return (calls, leaves, max_depth) for splitting the range [lo, hi)."""
if hi - lo <= 1:
return 1, hi - lo, depth
mid = lo + (hi - lo) // 2
c1, l1, d1 = count_calls(lo, mid, depth + 1)
c2, l2, d2 = count_calls(mid, hi, depth + 1)
return 1 + c1 + c2, l1 + l2, max(d1, d2)
print("n", "calls", "leaves", "depth", "ceil(log2 n)")
for n in [1, 2, 7, 8, 9, 1000, 100_000]:
calls, leaves, depth = count_calls(0, n)
print(n, calls, leaves, depth, math.ceil(math.log2(n)))Output:
n calls leaves depth ceil(log2 n)
1 1 1 0 0
2 3 2 1 1
7 13 7 3 3
8 15 8 3 3
9 17 9 4 4
1000 1999 1000 10 10
100000 199999 100000 17 17The output shows two patterns.
There are always 2n − 1 calls and n leaves. Every internal call has exactly two children, so the recursion tree is a full binary tree. A full binary tree with n leaves has n − 1 internal nodes, which gives n + (n − 1) = 2n − 1 nodes in total. This count holds however you choose mid, as long as both sides are non-empty.
The depth is ⌈log₂ n⌉. The larger half of a range of size n has ⌈n/2⌉ elements. After k levels the largest piece has ⌈n/2ᵏ⌉ elements, and that reaches 1 once 2ᵏ ≥ n. Unlike the call count, the depth does depend on splitting near the middle.
Why Halving Matters
The depth is about log₂ n because each split roughly halves the problem. Suppose you split at mid = lo + 1 instead. Every call would peel off one element and recurse on the other n − 1. The tree would still have 2n − 1 nodes, but its depth would be n − 1. That has two consequences:
- Each level of a merge sort tree does O(n) total merge work only when the levels are balanced. A lopsided tree turns the algorithm into something close to insertion sort, which is O(n²). The time-complexity chapter derives this properly.
- Python's default recursion limit is about 1000 frames. A balanced split of a list with 10¹⁸ elements reaches depth 60. A one-element-at-a-time split fails on a list of a few thousand elements.
| Split rule | Depth for n elements | Max stack frames at n = 1,000,000 | Calls |
|---|---|---|---|
| Halve (`mid = lo + (hi - lo) // 2`) | ⌈log₂ n⌉ | 21 | 2n − 1 |
| Peel one (`mid = lo + 1`) | n − 1 | 1,000,000 (crashes in Python) | 2n − 1 |
Common Errors in the Splitting Code
Most splitting bugs break one of the three guarantees from the start of the chapter. The table lists the usual ones.
| Bug | Code | What goes wrong |
|---|---|---|
| Base case misses the empty list | `if len(items) == 1: return` | Called on `[]`, `mid` is 0, and the right half `items[0:]` is `[]` again. The recursion never ends and raises `RecursionError`. |
| Mixing inclusive and half-open bounds | recurse on `(lo, mid)` and `(mid + 1, hi)` with half-open ranges | Element `mid` belongs to neither half and silently disappears from the output. |
| Inclusive bounds with half-open splitting | treat `hi` as included, recurse on `(lo, mid)` and `(mid, hi)` | Element `mid` lands in both halves. For a two-element range, `mid == lo`, so `(lo, hi)` calls itself forever. |
| Rounding `mid` badly | `mid = (lo + hi + 1) // 2` with base case `hi - lo < 1` | A one-element range gives `mid == hi`, so the right half is empty and the left half is the same range. The recursion loops. |
All four bugs come down to one invariant. For a half-open range that is not a base case, you need lo < mid < hi. If that holds, both halves are non-empty, both are strictly smaller than the parent, and together they cover the parent exactly. With hi - lo >= 2, both lo + (hi - lo) // 2 and lo + (hi - lo + 1) // 2 satisfy it. Which one you pick only decides which side gets the extra element.
A Note on the Cost of Slicing
The slicing version, items[:mid] and items[mid:], is easier to read and harder to get wrong, because Python's slices are half-open and clamp out-of-range bounds. But each slice allocates a new list. Across one level of the tree the slices copy n elements in total, and there are about log₂ n levels. That adds O(n log n) copying on top of the merge work, plus allocation churn. It does not change the overall Big-O of merge sort, but it is a constant-factor cost. The index-based version avoids it, and the chapter on auxiliary space covers what memory merge sort actually needs.
Exercises
Exercise
Without running code, give the number of calls, the number of leaves, and the maximum depth when count_calls splits a range of 13 elements.
Show answer
Calls = 2 × 13 − 1 = 25. Leaves = 13. Depth = ⌈log₂ 13⌉ = 4, since 2³ = 8 < 13 ≤ 16 = 2⁴. You can confirm the depth along the path of larger halves: 13 → 7 → 4 → 2 → 1, which is four splits.
Exercise
A colleague writes the base case as if len(items) == 1: return items and says it is fine because merge sort never produces an empty half. When does this fail, and what happens?
Show answer
Splitting a list of length 2 or more never produces an empty half, because floor division gives mid ≥ 1. The failure comes from the top-level call: merge_sort([]) skips the base case, computes mid = 0, and recurses on [] forever until Python raises RecursionError. Use len(items) <= 1 so empty input is handled too.
Exercise
Change count_calls to use mid = lo + 1. What does it report for n = 500, and why does n = 5000 fail in standard Python?
Show answer
For n = 500 it reports 999 calls, 500 leaves, and depth 499. The call count is still 2n − 1 because the tree is still a full binary tree with n leaves, but the depth is now n − 1. For n = 5000 the depth would be 4999, which is past Python's default recursion limit of about 1000, so it raises RecursionError.
Exercise
With half-open ranges, explain why lo < mid < hi guarantees that the recursion terminates and that no element is lost or duplicated.
Show answer
Because lo < mid, the range [lo, mid) is non-empty, and because mid < hi, [mid, hi) is non-empty. Each half is therefore strictly smaller than [lo, hi), so sizes keep decreasing until they reach the base case. The ranges [lo, mid) and [mid, hi) meet at mid without overlapping, and together they cover every index from lo to hi − 1 exactly once.