Sub topic 3
Bottom-Up Merge Sort Without Recursion
This chapter assumes you already know top-down merge sort, its merge step, and its O(n log n) time and O(n) space costs.
Bottom-Up Merge Sort Without Recursion
Bottom-up merge sort skips recursion. It treats every element as a sorted run of width 1, merges neighboring runs into runs of width 2, then 4, and keeps doubling until one run covers the whole array. It uses two buffers and swaps them after each pass, so it allocates only one extra array.
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]Sorting Linked Lists
On a singly linked list, you find the midpoint with a slow pointer and a fast pointer, cut the list in two, sort each half, and merge the halves by relinking nodes. No auxiliary array is needed. Linked lists don't support random access, which hurts quicksort and heapsort, so merge sort is the usual choice for them.
Practical Optimizations
- Switch to insertion sort for runs shorter than about 16–32 elements, because it has less overhead on small inputs.
- Skip a merge when
left[-1] <= right[0], because the two halves are already in order. - Timsort, used by Python's
sorted, finds runs that already exist in the data and merges them. This makes it close to O(n) on input that is nearly sorted.
Counting Inversions
An inversion is a pair of positions i < j where a[i] > a[j]. During a merge, each time you take an element from the right half first, it forms an inversion with every element still waiting in the left half. Adding len(left) - i at that moment counts all inversions in O(n log n) time.
External Merge Sort
External merge sort handles data too large for RAM. It reads memory-sized chunks, sorts each one, and writes it to disk as a sorted run. It then does a k-way merge of the runs, using a min-heap to choose the smallest head among the k runs.
Choosing an Algorithm
| Algorithm | Worst-case time | Extra space | Stable |
|---|---|---|---|
| Merge sort | O(n log n) | O(n) arrays, O(1) lists | Yes |
| Quicksort | O(n²) | O(log n) | No |
| Heapsort | O(n log n) | O(1) | No |
Choose merge sort when you need stability, guaranteed worst-case time, linked-list support, or external sorting. Quicksort is usually fastest on arrays in memory. Heapsort fits when memory is tight and you still need a worst-case bound.
Exercise
How many inversions does [3, 1, 2] contain, and in which merge are they counted?
Show answer
It contains 2 inversions: (3,1) and (3,2). The array splits into [3] and [1, 2]. The [1, 2] half has no inversions. In the final merge, 1 is taken before 3 (adding 1), then 2 is taken before 3 (adding 1), for a total of 2.