Sub topic 9
Bottom-Up Merge Sort Without Recursion
This chapter assumes you already know the merge step and the top-down recursive version from earlier chapters. You should also be comfortable reading nested loops and index arithmetic on Python lists.
Top-down merge sort splits the list in half, then in half again, until it reaches single elements, and merges as the calls return. The bottom-up version skips the splitting. It treats every element as a sorted run of length 1 and merges neighbouring runs. Runs of 1 become runs of 2, then 4, then 8, until one run covers the whole list. The comparisons are the same as in the recursive version. The difference is that a loop controls the order of merges instead of the call stack.
Why Avoid Recursion
The recursive version uses O(log n) stack frames, so the stack is rarely a problem. Bottom-up still has practical advantages:
- No recursion limit to think about. CPython's default limit is about 1000 frames, which matters if you adapt the code to other divide-and-conquer tasks.
- No list slicing. The top-down code in this tutorial copies
items[:mid]anditems[mid:]at every level. The bottom-up version allocates one extra buffer for the whole sort. - Predictable access patterns. Each pass reads the whole array from left to right, which caches handle well. External merge sort, covered later, uses the same pass structure.
The Pass Structure
A pass merges every pair of neighbouring runs of the current width. After the pass, width doubles. A list of n elements needs ⌈log₂ n⌉ passes, and each pass does O(n) work, so the total is still O(n log n).
In the width-2 pass, the run [1, 3] has no partner, so it is copied across unchanged. Leftover runs like this show up whenever n is not a power of two.
The Implementation
def merge_sort_bottom_up(items):
n = len(items)
src = list(items)
dst = [None] * n
width = 1
while width < n:
for lo in range(0, n, 2 * width):
mid = min(lo + width, n)
hi = min(lo + 2 * width, n)
i, j, k = lo, mid, lo
while i < mid and j < hi:
if src[i] <= src[j]:
dst[k] = src[i]
i += 1
else:
dst[k] = src[j]
j += 1
k += 1
while i < mid:
dst[k] = src[i]
i += 1
k += 1
while j < hi:
dst[k] = src[j]
j += 1
k += 1
src, dst = dst, src
width *= 2
return src
print(merge_sort_bottom_up([5, 2, 4, 6, 1, 3])) # [1, 2, 3, 4, 5, 6]Here is what each part does:
lo,mid,himark the left runsrc[lo:mid]and the right runsrc[mid:hi]. Themin(..., n)calls clip both bounds so the last pair can be short or missing.- The merge loop writes into
dstand uses<=, so ties take from the left run and the sort stays stable. src, dst = dst, srcswaps the two buffers rather than copying data back. After the swap, the output of this pass becomes the input of the next one.- The function returns
src, because after the final swap that is the buffer holding the last pass's output.
Common Errors
| Mistake | Symptom |
|---|---|
| Forgetting `min(..., n)` on `mid` or `hi` | `IndexError` when n is not a power of two |
| Skipping the copy of a lone leftover run | Stale values from two passes ago show up in the output |
| Returning `dst` instead of `src` | The result is one pass behind, so it is only partly sorted |
| Using `<` in the comparison | The output is still sorted, but equal keys can change order |
Exercises
Exercise
How many passes of the outer while loop run for a list of 10 elements, and what values does width take?
Show answer
Four passes, with width = 1, 2, 4, 8. The loop stops when width reaches 16, which is not less than 10. This matches ⌈log₂ 10⌉ = 4.
Exercise
Trace the width-2 pass on [2, 5, 4, 6, 1, 3]. What are lo, mid, and hi for the last group, and what happens to it?
Show answer
The last group has lo = 4, mid = min(6, 6) = 6, and hi = min(8, 6) = 6. The right run is empty, so the main merge loop does not run. The first copy loop moves 1 and 3 into dst[4] and dst[5] unchanged.
Exercise
Why does the bottom-up version allocate O(n) extra memory in total, while the slicing top-down version in this tutorial allocates more over a full run?
Show answer
The bottom-up version creates one extra n-element buffer and reuses both buffers on every pass. The top-down version creates new slices and new result lists at every level of recursion. At most O(n) of that memory is live at once, but the total allocated over the whole sort is O(n log n).