Sub topic 7
How Much Extra Memory Merge Sort Uses
This chapter assumes you have read the earlier chapters on the merge step and on top-down recursive merge sort. You should also be comfortable with Python lists, recursion and the call stack, and Big-O notation. The goal is a precise answer to one question: how much memory does merge sort need beyond the input itself, and which implementation choices change that amount?
What "auxiliary space" means
Auxiliary space is the memory an algorithm uses in addition to its input. A sort that rearranges elements using only a constant number of extra variables has O(1) auxiliary space and is called in-place. Merge sort on arrays is usually not in-place. Its standard form needs O(n) extra memory, and the recursion adds O(log n) for the call stack.
Merge sort's auxiliary space comes from two sources:
- Buffer space. This is the memory used to hold elements while two sorted runs are merged.
- Stack space. This is the memory used by the chain of active recursive calls.
When you analyse either one, separate the peak usage, meaning the most memory alive at one moment, from the total allocation across the whole run. Big-O space bounds describe the peak. The total still affects real performance, because every allocation costs time and adds work for the garbage collector.
Why the merge needs a buffer
Suppose the two sorted runs sit next to each other in one array: a[lo:mid] and a[mid:hi]. If you write the merged output straight into a[lo:hi], the first write can overwrite a left-half element you have not read yet. For example, if a[mid] is the smallest value, it must go to position lo. That destroys a[lo], which is still waiting to be merged.
The simple fix is to copy elements somewhere safe and merge back. That safe place is the buffer, and it is the reason the classic merge uses linear extra space.
The slicing version: O(n) peak, O(n log n) total
The top-down version from the earlier chapter uses slices such as items[:mid], and each one creates a new list. Here is what is alive at the deepest point of the recursion.
Only one path of calls is active at a time. Along that path, the call on n elements holds its two halves (n/2 each). Its child holds halves of n/4, and so on down the path. Not every slice on the path is alive at once, but even an upper bound gives a linear total:
n + n/2 + n/4 + ... + 1 < 2n
The partial result lists built by merges that have already finished at deeper levels are also still referenced while the parent merges. They are bounded by the same geometric series. The peak is therefore O(n).
The total allocation is larger. Every level of the recursion copies all n elements into new slices and builds n elements of merge output. With log₂ n levels, that comes to Θ(n log n) elements allocated and freed over the run. The space bound is fine, but this version does a lot of extra allocator work.
One preallocated buffer: O(n) with no churn
The standard fix is to allocate one auxiliary array of length n before sorting and pass index bounds instead of slices. Each merge copies a[lo:hi] into the same region of aux and merges back into a.
def merge_sort_buffered(a):
aux = [None] * len(a)
_sort(a, aux, 0, len(a))
return a
def _sort(a, aux, lo, hi):
if hi - lo <= 1:
return
mid = (lo + hi) // 2
_sort(a, aux, lo, mid)
_sort(a, aux, mid, hi)
_merge(a, aux, lo, mid, hi)
def _merge(a, aux, lo, mid, hi):
for k in range(lo, hi): # copy with a loop: a[lo:hi] would allocate a temp list
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
data = [38, 27, 43, 3, 9, 82, 10]
print(merge_sort_buffered(data)) # [3, 9, 10, 27, 38, 43, 82]The function sorts data in place and returns the same list object. The peak auxiliary memory is one list of n references plus O(log n) stack frames, and nothing is allocated after the first line.
Halving the buffer: copy only the left run
You do not need to copy both runs. Copy only the left run a[lo:mid] into the buffer, then merge the buffer and the right run a[mid:hi] forward into a[lo:hi].
This is safe because the write position k never passes the read position j in the right run. After you have taken p elements from the buffer and q from the right run, k = lo + p + q and j = mid + q. So k < j exactly when p < mid - lo, which means left elements remain. Once the buffer is empty, the rest of the right run is already in its final place, and you can stop.
def merge_sort_half_buffer(a):
aux = [None] * ((len(a) + 1) // 2)
_sort_half(a, aux, 0, len(a))
return a
def _sort_half(a, aux, lo, hi):
if hi - lo <= 1:
return
mid = (lo + hi) // 2
_sort_half(a, aux, lo, mid)
_sort_half(a, aux, mid, hi)
left_len = mid - lo
for t in range(left_len):
aux[t] = a[lo + t]
i, j, k = 0, mid, lo
while i < left_len and j < hi:
if aux[i] <= a[j]: # <= keeps the sort stable
a[k] = aux[i]
i += 1
else:
a[k] = a[j]
j += 1
k += 1
while i < left_len: # leftover right elements are already in place
a[k] = aux[i]
i += 1
k += 1
print(merge_sort_half_buffer([5, 2, 4, 6, 1, 3])) # [1, 2, 3, 4, 5, 6]The left half is mid - lo = (hi - lo) // 2 elements, so a buffer of ⌈n/2⌉ is always enough. Production merge sorts such as Timsort use the same idea: they copy the smaller of the two runs and merge from whichever end is safe. The bound stays Θ(n), but halving the constant matters when n is large.
Stack space
Each call splits its range in half, so the recursion depth is ⌈log₂ n⌉. Each frame holds a few indices, which gives O(log n) stack space. That is small next to the O(n) buffer. For a million elements, the depth is 20 frames, far below Python's default recursion limit of 1000. The iterative bottom-up variant, covered in a later chapter, removes the stack entirely but still needs the buffer.
What one "element" costs
In Python, a list stores references, so the buffer costs about 8 bytes per element on a 64-bit build no matter how large the objects are. The objects themselves are never copied. In C or Rust, sorting an array of large structs by value means the buffer holds full copies of those structs. A common workaround is to sort an array of indices or pointers and then rearrange the records once at the end.
Measuring it
You can watch the difference between the slicing version and the buffered version with tracemalloc, which tracks memory allocated by Python.
import random
import tracemalloc
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort_slicing(items):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge(merge_sort_slicing(items[:mid]), merge_sort_slicing(items[mid:]))
def merge_sort_buffered(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
def peak_kib(fn, data):
tracemalloc.start()
fn(data)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak / 1024
n = 200_000
base = [random.random() for _ in range(n)]
print("list of n refs ~", round(n * 8 / 1024), "KiB")
print("slicing peak ~", round(peak_kib(merge_sort_slicing, list(base))), "KiB")
print("buffered peak ~", round(peak_kib(merge_sort_buffered, list(base))), "KiB")The exact numbers depend on your Python version. Typically the buffered peak is close to one list of n references. The slicing peak is several times larger, and that version also runs slower because it allocates and frees Θ(n log n) elements over the run.
Summary of the variants
| Variant | Buffer (peak) | Stack | Total allocated over run | Notes |
|---|---|---|---|---|
| Slicing top-down | O(n), about 2–4n refs | O(log n) | Θ(n log n) | Simplest code, heavy allocator churn |
| One preallocated buffer | n | O(log n) | n | Standard textbook array version |
| Half buffer (copy left run) | ⌈n/2⌉ | O(log n) | ⌈n/2⌉ | Used in spirit by Timsort |
| Bottom-up with two buffers | n | O(1) | n | No recursion, covered later |
| Linked list (relinking) | O(1) | O(log n) | 0 | Covered later; no element copies |
| Block / in-place merge | O(1) | O(log n) or O(1) | 0 | Complex, slower constants |
Exercise
In the slicing version, the call on n elements is merging two sorted halves of size n/2. Which lists are alive at that moment, and why is the peak still O(n) even though Θ(n log n) elements are allocated in total?
Show answer
The live lists are the call's own input (n), its two half-slices (n/2 each), the two sorted halves returned by its children (n/2 each), and the growing result (up to n), plus the inputs held by its ancestors on the call path, which sum to less than 2n. Every one of these terms is a constant multiple of n, so the peak is O(n). The Θ(n log n) total comes from lists created at deeper levels that have already been freed. They are never alive at the same time.
Exercise
In the half-buffer merge, explain why the loop can stop as soon as the buffered left run is used up, without copying the remaining right-run elements.
Show answer
The right run already sits in a[mid:hi], in sorted order. Once all left elements are placed, the write index k equals the read index j, so the remaining right elements a[j:hi] are already in their final positions.
Exercise
You must sort 10 million 200-byte records in C with merge sort, and memory is tight. Give two changes that reduce auxiliary memory, and state the cost of each.
Show answer
First, sort an array of 4- or 8-byte indices or pointers instead of the records. The buffer then shrinks from about 2 GB to 40–80 MB, at the cost of indirect comparisons and one final permutation pass. Second, buffer only the smaller run, which halves the buffer and costs a little extra code complexity. A fully in-place block merge sort would remove the buffer entirely, but it is harder to implement and slower.