Sub topic 7
How Much Extra Memory Merge Sort Uses
This chapter assumes you know the top-down merge sort from the previous chapters, how recursion uses the call stack, and Big-O notation. Merge sort's running time is fixed at O(n log n). Its memory use depends on how you implement it, so you need a clear way to measure it.
Two Kinds of Extra Memory
Auxiliary space is the memory an algorithm uses beyond the input itself. Merge sort uses two kinds:
- Merge buffers. Merging two sorted halves of an array needs somewhere to put the output. You cannot write the merged result over the input without losing elements you have not read yet.
- Call stack frames. Each recursive call keeps a stack frame alive until it returns. Halving gives a recursion depth of about log₂ n, so the stack costs O(log n).
The buffers dominate. For arrays, merge sort needs Θ(n) auxiliary space, compared with O(log n) for a typical quicksort and O(1) for heapsort.
Peak Memory Versus Total Allocation
The slicing version from earlier, merge(merge_sort(items[:mid]), merge_sort(items[mid:])), copies data at every level. Across the whole run it allocates about n log n list slots. Most of those lists become garbage quickly, though. What limits you is peak live memory, meaning the most memory in use at any one moment.
Follow a single path down the recursion. While the deepest call runs, the lists still alive are a slice of size n/2 at depth 1, a slice of size n/4 at depth 2, and so on. Each level also holds a finished result of the same size from its sibling call. The sum n/2 + n/4 + … is less than n, so the peak stays O(n). The constant is larger than necessary, and the many allocations make the allocator do extra work.
One Shared Buffer
Production implementations allocate one auxiliary array of size n at the start and reuse it for every merge. Each merge copies its range into the buffer and then merges back into the original array. Extra space is then exactly n slots plus O(log n) stack.
def merge_sort_shared(a):
aux = [None] * len(a)
def sort(lo, hi):
if hi - lo <= 1:
return
mid = (lo + hi) // 2
sort(lo, mid)
sort(mid, hi)
for k in range(lo, hi):
aux[k] = a[k]
i, j = lo, mid
for k in range(lo, hi):
if i < mid and (j >= hi or aux[i] <= aux[j]):
a[k] = aux[i]
i += 1
else:
a[k] = aux[j]
j += 1
sort(0, len(a))
return a
print(merge_sort_shared([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]The copy loop runs explicitly instead of using aux[lo:hi] = a[lo:hi], because the right-hand slice would build a temporary list on every merge.
Space by Variant
| Variant | Merge buffers | Stack | Total auxiliary |
|---|---|---|---|
| Slicing top-down (Python lists) | O(n) peak, O(n log n) allocated | O(log n) | O(n) |
| Shared buffer top-down | n slots | O(log n) | O(n) |
| Bottom-up with two buffers | n slots | O(1) | O(n) |
| Linked list, recursive | none | O(log n) | O(log n) |
| In-place merge variants | O(1) | O(log n) | O(log n), but slower and complex |
In-place merging algorithms exist. They either give up the linear-time merge or need intricate block rotations, so standard libraries rarely use them. Linked lists avoid the buffer by relinking nodes, as a later chapter shows.
Common Errors
- Calling the slicing version "O(n log n) space." Its total allocation is O(n log n), but its peak is O(n).
- Allocating a new buffer inside every merge call. The peak stays O(n), but you pay allocation costs n times.
- Forgetting the stack when you claim O(1) extra space for a recursive version.
Exercise
You sort a Python list of 10 million integers with mergesortshared. Roughly how much memory does the aux list add on a 64-bit system, and what does the recursion stack add?
Show answer
The aux list holds 10 million references at 8 bytes each, about 80 MB (the integer objects themselves are shared, not copied). The recursion depth is about log₂(10⁷) ≈ 24 frames, which is negligible beside the buffer.
Exercise
Why can't the merge simply write its output into a[lo:hi] while reading from a[lo:mid] and a[mid:hi], with no buffer?
Show answer
When the right half supplies an element first, writing it at position k overwrites a left-half element that has not been read yet, so data is lost. Avoiding that requires shifting elements, which makes each merge O(n²) in the worst case.