Merge sort is divide-and-conquer made concrete: split the array into two halves, recursively sort each half, then merge the two sorted halves into one sorted whole. The base case is a single element, trivially sorted. The magic is in the merge: given two sorted lists, one linear pass with two pointers produces a sorted union. No comparisons are ever wasted.
The complexity analysis is a beautiful recurrence: T(n) = 2T(n/2) + O(n), two half-size subproblems plus a linear merge. The recursion tree has log₂(n) levels (halving each time), and each level does O(n) total merge work, giving O(n log n), on EVERY input. No adversarial case, no lucky case. That predictability plus stability (equal elements merge left-first, preserving order) is why merge sort underlies Timsort, the default sort of Python and Java.
Implementation
// Pure: returns a new sorted array. Stable. O(n) extra space.
function mergeSort(arr) {
if (arr.length <= 1) return [...arr]; // base case
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid)); // conquer left half
const right = mergeSort(arr.slice(mid)); // conquer right half
return merge(left, right); // combine
}
function merge(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) out.push(a[i++]); // <= keeps it stable: left wins ties
else out.push(b[j++]);
}
while (i < a.length) out.push(a[i++]); // drain the leftovers
while (j < b.length) out.push(b[j++]);
return out;
}Trace: [38, 27, 43, 3]
- 1
Split down
[38, 27, 43, 3] → [38, 27] + [43, 3] → [38] + [27] and [43] + [3]. Four singletons, all trivially sorted.
- 2
Merge up (level 1)
merge([38], [27]): 27 ≤ 38 → [27, 38]. merge([43], [3]) → [3, 43].
- 3
Merge up (level 2)
merge([27, 38], [3, 43]): 3<27 take 3; 27<43 take 27; 38<43 take 38; drain 43 → [3, 27, 38, 43].
- 4
Cost audit
2 levels of halving ⇒ log₂4 = 2; each level merged 4 elements total ⇒ O(n log n) = 8 merge-steps. Compare bubble sort's worst case of 6 comparisons on just 4 items, the gap explodes as n grows.
| Operation / case | Cost | Notes |
|---|---|---|
| Time (best, average, worst) | O(n log n) | input-independent, its superpower |
| Space | O(n) | merge buffer + recursion O(log n) |
| Stable? | Yes | with the <= tie-break in merge |
| Parallelizes? | Yes | halves sort independently |