Algorithm Deep Dives

Merge Sort Explained

Updated June 8, 2026 7 min read

Merge Sort is the textbook divide-and-conquer algorithm. It splits the array in half, recursively sorts each half, then merges the two sorted halves into one. It guarantees O(n log n) time on every input and is stable, making it a favourite when predictability matters.

How Merge Sort works

The algorithm has two phases. Divide: recursively split the array until each piece has a single element (which is trivially sorted). Conquer: repeatedly merge pairs of sorted pieces by walking two pointers and always taking the smaller front element, until one fully sorted array remains.

Pseudocode

mergeSort(a):
  if length(a) <= 1: return a
  mid = length(a) / 2
  left = mergeSort(a[0..mid])
  right = mergeSort(a[mid..end])
  return merge(left, right)

merge(L, R):
  result = []
  while L and R not empty:
    if L[0] <= R[0]: result.push(L.shift())
    else: result.push(R.shift())
  return result + L + R

Complexity and stability

Merge Sort is O(n log n) in best, average, and worst case — the log n comes from halving the array, the n from each merge level touching every element. It needs O(n) auxiliary space for the merge buffer, so it is not in-place. It is stable, which is why Java uses it (as Tim Sort) for sorting objects.

External sorting and when to choose it

Because Merge Sort accesses data sequentially and merges streams, it is the standard approach for external sorting — sorting files too large to fit in RAM. Choose Merge Sort when you need guaranteed O(n log n), stability, or are sorting linked lists. Compare it with Quick Sort in our popular head-to-head.

Frequently asked questions

What is the time complexity of Merge Sort? +
Merge Sort is O(n log n) in all cases — best, average, and worst. Its space complexity is O(n) due to the temporary merge buffer.
Is Merge Sort stable? +
Yes. When merging, equal elements take the one from the left half first, preserving their original relative order. This makes Merge Sort the basis for stable library sorts.
Why is Merge Sort good for large datasets? +
It guarantees O(n log n) regardless of input and accesses data sequentially, which makes it ideal for external sorting of data that does not fit in memory.

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles