merge sort
space complexity
array
algorithm analysis
computer science

space complexity of merge sort using array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Merge sort is famous for reliable O(n log n) time complexity, but its memory use is equally important in real systems. When implemented with arrays, merge sort typically needs extra storage during merge steps. This article explains where that memory goes and how different implementations affect total space complexity.

Core Space Components

For array-based merge sort, memory usage usually comes from two sources.

  • Auxiliary array used during merge operations.
  • Recursion stack frames from divide-and-conquer calls.

The auxiliary array is usually the dominant term.

Standard Top-Down Merge Sort Space Analysis

A common implementation allocates one temporary array of size n and reuses it for all merge operations.

python
1def merge_sort(arr):
2    temp = [0] * len(arr)
3
4    def sort(lo, hi):
5        if lo >= hi:
6            return
7        mid = (lo + hi) // 2
8        sort(lo, mid)
9        sort(mid + 1, hi)
10        merge(lo, mid, hi)
11
12    def merge(lo, mid, hi):
13        i, j, k = lo, mid + 1, lo
14        while i <= mid and j <= hi:
15            if arr[i] <= arr[j]:
16                temp[k] = arr[i]
17                i += 1
18            else:
19                temp[k] = arr[j]
20                j += 1
21            k += 1
22
23        while i <= mid:
24            temp[k] = arr[i]
25            i += 1
26            k += 1
27
28        while j <= hi:
29            temp[k] = arr[j]
30            j += 1
31            k += 1
32
33        for p in range(lo, hi + 1):
34            arr[p] = temp[p]
35
36    sort(0, len(arr) - 1)

Space usage for this style:

  • Temporary array: O(n).
  • Recursion stack depth: O(log n).
  • Total asymptotic space: O(n).

The O(log n) stack term is lower order relative to O(n).

Why Temporary Storage Is Needed

Merge operation combines two sorted halves into one sorted range. If you overwrite source values too early without extra storage, unread values can be lost. The temporary buffer preserves data integrity and keeps merge logic simple and stable.

Stability means equal elements keep original relative order, which is often required for multi-key sorting workflows.

Bottom-Up Merge Sort Space Behavior

Iterative bottom-up merge sort removes recursion, so stack usage drops to constant. It still needs merge buffer space.

javascript
1function mergeSortIterative(arr) {
2  const n = arr.length;
3  const temp = new Array(n);
4
5  for (let width = 1; width < n; width *= 2) {
6    for (let left = 0; left < n; left += 2 * width) {
7      const mid = Math.min(left + width, n);
8      const right = Math.min(left + 2 * width, n);
9
10      let i = left, j = mid, k = left;
11      while (i < mid && j < right) {
12        temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
13      }
14      while (i < mid) temp[k++] = arr[i++];
15      while (j < right) temp[k++] = arr[j++];
16      for (let p = left; p < right; p++) arr[p] = temp[p];
17    }
18  }
19}

Total space remains O(n) because the auxiliary array still dominates.

Can Merge Sort Be In-Place

There are in-place merge variants with lower extra memory, but they are significantly more complex and often slower in practice due to many element moves and poor cache behavior. For most applications, standard O(n) extra space merge sort is preferred for simplicity and predictable performance.

Practical Memory Considerations

The asymptotic label is useful, but real memory pressure depends on element size and runtime overhead.

  • Sorting 10 million integers requires substantial temporary buffer memory.
  • In managed runtimes, additional object overhead can amplify memory footprint.
  • Reusing one auxiliary array is better than allocating a new one in each recursive call.

If memory is tight, compare with in-place alternatives such as heap sort or tuned quicksort variants.

Common Pitfalls

  • Claiming merge sort uses O(log n) space while ignoring auxiliary array.
  • Allocating fresh temporary arrays in every merge, increasing allocation cost.
  • Forgetting recursion stack contribution in top-down implementations.
  • Assuming in-place merge implementations are simple drop-in replacements.
  • Choosing merge sort in memory-constrained environments without measuring footprint.

Summary

  • Array-based merge sort usually requires O(n) extra space for merge buffer.
  • Recursive top-down version adds O(log n) stack space, still dominated by O(n).
  • Iterative bottom-up version removes recursion but still needs auxiliary array.
  • In-place merge techniques exist but are complex and often slower.
  • Practical memory planning should consider data size, runtime overhead, and allocation strategy.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.