Merge sort
Merge sort splits the array in half, sorts each half recursively and merges the sorted halves. It always takes O(n log n) time and is stable.
Before you start: Recursion: base case, recursive case, the call stack.
The idea
Two teachers hand you sorted piles of exams. You combine them by taking the smaller top sheet, again and again.
Combining two sorted piles is easy: one look at each top sheet decides what comes next. Merge sort turns any sorting job into many of these easy merges.
Intuition
Cut the array in half. Keep cutting each half until every part holds one value, and one value is sorted.
Two sorted halves merge by comparing only their front values. The smaller front goes into a buffer next.
Each comparison moves one value into the buffer, so merging two halves of total size n takes at most n - 1 comparisons.
Complexity
The split tree has about log2 n levels, and the merges on each level touch n values. That gives O(n log n) on every input.
Merge sort does the same splits and the same merge work whether the input is sorted, reversed or random. For 1,000 values that is about 10,000 steps instead of 500,000.
The last merge needs a buffer as long as the array. Extra space is O(n), plus O(log n) for the calls.
Pitfalls
When the fronts are equal, take the left one. With a[i] < a[j] 5R goes before 5L and the sort is no longer stable.
The loop stops as soon as one side is used up. Forget to copy the rest and 5 is lost.
Variations
Bottom-up merge sort skips recursion and merges runs of 1 into runs of 2, then 4, then 8. Timsort builds on this idea.
On a linked list, merging only relinks nodes. No buffer is needed, so merge sort is the usual way to sort lists.
Code
Pseudocode
sort(a, lo, hi)
if lo = hi: return
mid ← (lo + hi) / 2
sort(a, lo, mid); sort(a, mid + 1, hi)
i ← lo, j ← mid + 1, buf ← []
while i ≤ mid and j ≤ hi
if a[i] ≤ a[j]: append a[i] to buf, i ← i + 1
else: append a[j] to buf, j ← j + 1
append a[i..mid] and a[j..hi] to buf
copy buf into a[lo..hi]
Python
def merge_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return a
mid = (lo + hi) // 2
merge_sort(a, lo, mid)
merge_sort(a, mid + 1, hi)
i, j, buf = lo, mid + 1, []
while i <= mid and j <= hi:
if a[i] <= a[j]:
buf.append(a[i]); i += 1
else:
buf.append(a[j]); j += 1
buf += a[i:mid + 1] + a[j:hi + 1]
a[lo:hi + 1] = buf
return a
JavaScript
function mergeSort(a, lo = 0, hi = a.length - 1) {
if (lo >= hi) return a;
const mid = Math.floor((lo + hi) / 2);
mergeSort(a, lo, mid);
mergeSort(a, mid + 1, hi);
let i = lo, j = mid + 1;
const buf = [];
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) buf.push(a[i++]);
else buf.push(a[j++]);
}
while (i <= mid) buf.push(a[i++]);
while (j <= hi) buf.push(a[j++]);
for (let k = 0; k < buf.length; k++) a[lo + k] = buf[k];
return a;
}
Java
static void mergeSort(int[] a, int lo, int hi) {
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
mergeSort(a, lo, mid);
mergeSort(a, mid + 1, hi);
int[] buf = new int[hi - lo + 1];
int i = lo, j = mid + 1, k = 0;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) buf[k++] = a[i++];
else buf[k++] = a[j++];
}
while (i <= mid) buf[k++] = a[i++];
while (j <= hi) buf[k++] = a[j++];
System.arraycopy(buf, 0, a, lo, buf.length);
}
Cost at a glance
| Best | O(n log n) |
|---|---|
| Average | O(n log n) |
| Worst | O(n log n) |
| Space | O(n) |
| Stable | yes |
| In-place | no |
| Adaptive | no |
Practice problems (6)
Recursion depth Warm-up
Merge sort runs on the 8 values [5, 2, 4, 7, 1, 3, 2, 6]. Watch the split tree grow and answer the questions about its depth.
Breaking a tie in the merge Warm-up
The merge compares the fronts of the left half [3, 5] and the right half [5, 7]. 3 is already in the buffer, and both fronts are now 5. Which choice keeps merge sort stable?
Merge two sorted arrays Standard
a and b are both sorted ascending. Return one sorted array that holds every value of both. Walk both arrays once with two pointers; do not call a sort function.
Implement merge sort Standard
Sort nums ascending with merge sort and return the sorted array. Split the range in half, sort each half recursively, then merge the two sorted halves through a buffer.
The largest test has 10,000 values, so an O(n²) sort is too slow.
Sort a linked list Standard
Sort a singly linked list ascending in O(n log n) time and return the new head. Relink the existing nodes.
Find the middle with a slow and a fast pointer, cut the list there, sort both halves recursively and merge them by relinking.
Count inversions Challenge
An inversion is a pair of indices i < j with nums[i] > nums[j]. Return the number of inversions in nums.
The largest tests have 50,000 values, so checking every pair (O(n²)) is too slow. Count the pairs while merge sort merges.
Related topics
Next on the path: Quick sort: partitioning and pivots