Merge Sort Variants
Compare recursive splits, iterative merges, and safe merge optimisations.
merge sort, bottom up, top down, optimisation, sortingBuild small ordered piles
The merge sort lesson splits a row recursively, then merges the ordered halves. That is top-down: start with the whole job and break it down. Bottom-up starts with single cards, which are already sorted, and merges neighbouring runs into larger runs.
Why use these variants
Both approaches give predictable O(n log n) sorting time and can be stable. Bottom-up avoids recursive calls. Top-down lets a program stop splitting small ranges and use another method there. The right choice depends on the data, memory, and implementation, not just the name of the algorithm.
Follow bottom-up merging
Start: [4] [1] [3] [2] [5]
size 1: [1, 4] [2, 3] [5]
size 2: [1, 2, 3, 4] [5]
size 4: [1, 2, 3, 4, 5]
At each pass, merge adjacent runs of the current size. The final run may be shorter than the others, and an unpaired run is carried forward.
See the reasoning
Follow the example one step at a time
Build bigger ordered runs with bottom-up merge sort. This is a prepared teaching demonstration, not live code execution.
Start with single items
[4] [1] [3] [2] [5]
Each single-item run is already sorted.
Python illustration
def bottom_up_merge_sort(numbers):
items = numbers[:]
width = 1
while width < len(items):
merged = []
for start in range(0, len(items), 2 * width):
left = items[start:start + width]
right = items[start + width:start + 2 * width]
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:])
items = merged
width *= 2
return items
print(bottom_up_merge_sort([4, 1, 3, 2, 5]))
print(bottom_up_merge_sort([]))
Prepared output — not live execution:
[1, 2, 3, 4, 5]
[]
The example returns a new list and handles a final short run. Choosing from the left on ties preserves stability for items with a consistent comparison.
Optimisations and costs
A top-down implementation can use insertion sort for small subarrays. It can also skip merging when the last item of the sorted left half is no greater than the first item of the sorted right half. These checks are valid only after both halves are sorted. Reusing an auxiliary array can reduce allocations. The code above does not implement these optimisations.
There are O(log n) passes, each processing O(n) items, for O(n log n) time. The example holds copied lists and a result, using O(n) extra space. A recursive top-down version also uses O(log n) call-stack depth for balanced splits. Skipping a merge must not skip the recursive work needed to sort its children.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
