Sub topic 9
Bottom-Up Merge Sort Without Recursion
This chapter assumes you already know the merge step and the top-down recursive merge sort from earlier chapters. It also assumes you are comfortable with Python list indexing, slicing, and Big-O notation. We will remove the recursion completely. The algorithm still does the same merging, but it organizes the work as a loop over fixed-size runs.
The Idea: Start From the Leaves
Top-down merge sort splits the array in half again and again until each piece has one element. Then it merges the pieces back together as the recursion unwinds. All of the real work happens during the merges. The splitting only decides which ranges get merged.
Bottom-up merge sort skips the splitting phase. A run is a contiguous slice of the array that is already sorted. Any single element counts as a sorted run of length 1. So an array of n elements already holds n sorted runs, and we can start merging right away:
- Merge neighboring runs of width 1 into sorted runs of width 2.
- Merge neighboring runs of width 2 into sorted runs of width 4.
- Keep doubling the width until one run covers the whole array.
Each round of merges across the whole array is called a pass. After the pass with width w, every aligned block of 2w elements is sorted. The last block may be shorter.
The odd element 10 has no partner in the first pass. It gets copied forward unchanged and joins a merge in a later pass. Handling these leftover runs correctly is the main detail that separates a working bottom-up sort from a broken one.
The Implementation
The version below allocates one extra array. Each pass reads from src and writes into dst. After the pass, the two names are swapped, so the output of one pass becomes the input of the next. Nothing gets copied back between passes.
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]Reading the Index Arithmetic
For each pass, lo steps through the array in jumps of 2 * width. Each step marks the start of a pair of runs:
- The left run is
src[lo:mid]. - The right run is
src[mid:hi]. - The merged result goes into
dst[lo:hi].
Both mid and hi are clamped with min(..., n), which covers two edge cases at the end of the array:
| Situation at the tail | `mid` | `hi` | What happens |
|---|---|---|---|
| Full pair of runs | `lo + width` | `lo + 2*width` | Normal merge |
| Right run is shorter than `width` | `lo + width` | `n` | Merge with a short right run |
| No right run at all | `n` | `n` | The left run is copied to `dst` as is |
In the third case the main loop never runs, because j < hi is false from the start. The while i < mid loop then copies the leftover run into dst.
Watching the Passes
A small instrumented version prints the array after each pass. It also moves the merge into a helper function so the loop structure is easier to see.
def merge_runs(src, dst, lo, mid, hi):
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
dst[k:hi] = src[i:mid] + src[j:hi]
def bottom_up_trace(items):
n = len(items)
src, dst = list(items), [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)
merge_runs(src, dst, lo, mid, hi)
src, dst = dst, src
print(f"after width {width}: {src}")
width *= 2
return src
bottom_up_trace([38, 27, 43, 3, 9, 82, 10])
# after width 1: [27, 38, 3, 43, 9, 82, 10]
# after width 2: [3, 27, 38, 43, 9, 10, 82]
# after width 4: [3, 9, 10, 27, 38, 43, 82]The slice assignment dst[k:hi] = src[i:mid] + src[j:hi] copies whichever run still has elements left. At most one of the two slices is non-empty, and their combined length is exactly hi - k, so the list keeps its size.
Common Errors
Skipping the Leftover Run
A tempting "optimization" is to skip any block that has no right run:
if mid >= hi:
continue # BUGThat looks harmless because the leftover run is already sorted. The bug comes from the buffer swap. The skipped elements are never written into dst. After the swap, src holds whatever that buffer held two passes ago, which is stale data or None. You have to copy every element into dst on every pass. The alternative is to switch to a design that copies back into one fixed array after each pass, which costs an extra copy per pass.
Returning the Wrong Buffer
After the final swap, the sorted data is in src, not dst. Returning dst gives you the array from one pass earlier. If you want to sort the caller's list in place, finish with items[:] = src.
Using `<` Instead of `<=`
The comparison src[i] <= src[j] takes from the left run on ties. The left run always holds elements that came earlier in the original order, so this keeps the sort stable, as described in the stability chapter. Changing it to < still sorts correctly, but equal keys can come out in a different order.
Off-by-One in the Loop Condition
The loop condition is while width < n. With width <= n, a power-of-two n gets one extra pass. That pass only copies the full sorted run, so the result is still correct, but it wastes time. Using width < n // 2 stops too early and leaves two unmerged halves.
How It Compares to Top-Down
Both versions perform merges of sorted runs, and both run in Θ(n log n) time. The number of passes is ⌈log₂ n⌉, and each pass touches every element once. They differ in a few practical ways.
| Property | Top-down | Bottom-up |
|---|---|---|
| Control structure | Recursion | Two nested loops |
| Call stack depth | O(log n) frames | O(1) |
| Split points for n = 6 | 3 + 3 | 4 + 2 |
| Auxiliary array | O(n) | O(n) |
| Memory access pattern | Depth-first, jumps between subproblems | Sequential sweeps across the array |
| Run sizes | Balanced at every level | Powers of two, plus one short tail run |
The split points are the least obvious difference. Top-down halves each range, so its runs are always balanced. Bottom-up always uses power-of-two widths, so when n is not a power of two the final merge can be lopsided. For example, with n = 1025 the last pass merges a run of 1024 elements with a run of 1. That costs no more than a balanced merge, and the asymptotic bound stays the same. The comparison count does differ slightly, though, and the two versions can produce different intermediate states.
When Bottom-Up Is the Better Choice
- No recursion available or wanted. Some embedded environments, GPU kernels, and languages with small stack limits make recursion awkward. Python's default recursion limit is not a problem at depth log n, but a non-recursive design avoids the question entirely.
- Sequential access. Each pass reads and writes the array from left to right. That pattern suits caches, and it matches the merging of runs stored on disk, which the external merge sort chapter builds on.
- Linked lists. Bottom-up merging of lists needs no midpoint search. The linked-list chapter shows the recursive version for comparison.
- Natural runs. Instead of starting with width 1, you can first scan for runs that are already sorted and merge those. This variant is called natural merge sort, and it is the starting point for the hybrid sorts covered in the optimizations chapter.
Correctness in One Sentence
The loop invariant is: at the start of the pass with width w, every aligned block src[m*w : (m+1)*w] is sorted, with the last block possibly shorter. The invariant holds for w = 1. Merging adjacent pairs of sorted blocks produces sorted blocks of width 2w, so it holds for the next pass. When w >= n, the single block is the whole array.
Exercise
How many passes does mergesortbottom_up make on a list of 1000 elements, and how many on a list of 1024 elements?
Show answer
It makes ⌈log₂ n⌉ passes. For 1000 elements, the widths are 1, 2, 4, ..., 512, which is 10 passes, because 2^10 = 1024 ≥ 1000. For 1024 elements it is also 10 passes. The loop stops when width reaches 1024, which is not less than n.
Exercise
A colleague adds if mid >= hi: continue inside the for loop of mergesortbottom_up to avoid copying a lone leftover run. Run it mentally on [3, 2, 1]. What goes wrong?
Show answer
Pass width 1: block lo=0 merges [3] and [2] into dst[0:2] = [2, 3]. Block lo=2 has mid = hi = 3, so it is skipped, and dst[2] stays None. After the swap, src = [2, 3, None]. Pass width 2 then compares 2 or 3 against None, which raises a TypeError in Python 3. Every element must be written into dst on every pass.
Exercise
For the input [4, 3, 2, 1, 0, 9], list the pairs of runs merged in the final pass by top-down merge sort and by bottom-up merge sort.
Show answer
Top-down splits 6 into 3 + 3, so its final merge combines [2, 3, 4] with [0, 1, 9]. Bottom-up's final pass has width 4, so it merges the first four elements, sorted as [1, 2, 3, 4], with the last two, sorted as [0, 9]. Both produce [0, 1, 2, 3, 4, 9].
Exercise
Modify mergesortbottom_up so it sorts the caller's list in place (the function returns None and the original list object ends up sorted). What single line do you add?
Show answer
Add items[:] = src after the while loop, and drop the return or return None. Slice assignment replaces the contents of the caller's list object, while items = src would only rebind the local name.