Merge sort works by splitting an array in half repeatedly until each piece holds one element, then merging those pieces back together in sorted order. Each merge compares only the front elements of two already-sorted runs and appends the smaller one to the output. That single rule produces a complete sort in O(n log n) time, every time, regardless of input order.

The algorithm is a canonical example of divide and conquer: break the problem into independent subproblems, solve each recursively, and combine the results. What makes merge sort distinctive is that the combining step, not the splitting step, does all the real work. Splitting is trivial; merging is where order emerges.

This explainer goes one level deeper than the standard summary. It covers the exact comparison mechanics inside a merge, the arithmetic behind the n log n bound, the memory cost that shows up in production systems, and the specific conditions under which merge sort beats or loses to quicksort, heapsort, and Timsort.

The split-merge mechanism, step by step

Merge sort runs two distinct phases. The divide phase is pure recursion: find the midpoint, split the array into left and right halves, and recurse on each. The divide phase performs no comparisons and does no sorting. It exists only to reduce the problem size until every subarray has exactly one element, and a one-element array is sorted by definition.

The conquer phase does the work. Two sorted runs are merged by maintaining a pointer at the front of each run. Compare the two front elements, copy the smaller one into the output buffer, and advance that pointer. When one run is exhausted, copy the remainder of the other run wholesale, because it is already sorted.

Why the merge step is correct

The correctness argument rests on one invariant: at every moment, the smallest remaining element across both runs sits at one of the two pointers. Each run is sorted, so its smallest element is at its front. The smaller of the two fronts is therefore the smallest element overall. Appending it to the output is always safe.

This is why merge sort needs no comparisons beyond the fronts. It never inspects the interior of either run. A merge of two runs totaling n elements performs at most n − 1 comparisons, because each comparison consumes one element and the last element is copied without a comparison.

Why the recursion terminates cleanly

The base case is a subarray of length 0 or 1, which is already sorted. On a 64-bit machine with a typical midpoint calculation, recursion depth for an array of n elements is ⌈log₂ n⌉ + 1. For one million elements that is about 21 levels. The call stack cost is proportional to log n, not n, which is why merge sort does not blow the stack on large inputs the way naive quicksort can on adversarial data.

Why the algorithm is stable

Stability means equal elements keep their original relative order. Merge sort achieves this with a single tie-breaking rule: when the front elements of the two runs are equal, take the one from the left run first. That one line is the entire mechanism behind stability. It matters whenever records carry a sort key plus associated payload, such as sorting transactions by date while preserving insertion order within each date.

Quantified context: the arithmetic of n log n

The recurrence relation for merge sort is T(n) = 2T(n/2) + O(n). The 2T(n/2) term is the two recursive halves; the O(n) term is the linear merge. The recursion tree has log₂ n levels, and each level performs O(n) total merge work across all subproblems. Multiplying gives O(n log n).

For 1,000 elements, log₂ 1000 is about 9.97, so the comparison count lands near 10,000 in the worst case. For one million elements, log₂ 1,000,000 is about 19.93, so the bound is roughly 20 million comparisons. Doubling the input from n to 2n adds only one recursion level and roughly one extra n of work per element, which is why the curve stays close to linear on log-scaled plots.

The worst case and average case are identical. Merge sort performs the same number of comparisons and the same memory operations whether the input is random, sorted, reverse-sorted, or pathological. That predictability is its selling point in latency-sensitive systems.

One professional caveat: the O(n) auxiliary buffer is not optional in the standard implementation. In-place merge sort variants exist and reduce auxiliary space to O(log n) or even O(1), but they typically multiply the constant factor on comparisons and moves, often by a factor between 2 and 4 in published implementations. The space saving is real; the speed cost is also real.

Edge cases and the counterintuitive details

The most counterintuitive fact about merge sort is that it can be slower than insertion sort on small inputs and still be the right choice overall. Insertion sort has a tiny constant factor and excellent cache behavior on arrays under roughly 16 to 32 elements. Production implementations therefore stop recursing at that threshold and switch to insertion sort, a technique called a hybrid or cutoff optimization. Timsort, the default sort in Python and Java's object sort, uses exactly this structure plus run detection.

Another counterintuitive detail concerns nearly sorted data. Adaptive merge sort variants detect existing sorted runs and merge them directly, so a nearly sorted array can drop well below the n log n bound. Standard merge sort does not do this; it pays the full price regardless.

Edge cases worth naming:

An empty array and a single-element array return immediately with zero comparisons; the recursion base case handles both. Duplicate keys are handled correctly only if the left-run tie-break is present; omit it and stability silently breaks. The midpoint calculation must avoid integer overflow: (low + high) / 2 overflows on very large indices, so the safe form is low + (high − low) / 2. Arrays larger than available memory require external merge sort, which merges sorted runs from disk in passes; the comparison logic is identical but I/O dominates. Linked lists are a natural fit because merging two lists needs O(1) extra space, no buffer, and pointer relinking replaces element copying. Recursion depth on huge arrays should be checked against the stack limit; an iterative bottom-up merge avoids the call stack entirely.

One more professional caveat: merge sort is not a good choice when the data is mostly sorted and the workload is latency-critical, because standard merge sort cannot exploit existing order. Timsort and adaptive variants can, but plain textbook merge sort cannot.

Comparison table: merge sort versus the field

Algorithm Average time Worst time Extra space Stable Notes
Merge sort O(n log n) O(n log n) O(n) Yes Predictable; needs buffer
Quicksort O(n log n) O(n²) O(log n) No Fast in practice; adversarial worst case
Heapsort O(n log n) O(n log n) O(1) No In-place; poor cache locality
Insertion sort O(n²) O(n²) O(1) Yes Excellent under ~16–32 elements
Timsort O(n log n) O(n log n) O(n) Yes Adaptive; exploits existing runs
Counting sort O(n + k) O(n + k) O(n + k) Yes Integer keys in a bounded range only

The table explains the practical hierarchy. Quicksort usually wins on raw speed for in-memory arrays because its partition step has better cache behavior. Merge sort wins when stability is required, when worst-case guarantees matter, or when the data lives on disk or in a linked structure.

Timeline table: what happens inside one merge of two 4-element runs

Step Left front Right front Action Output so far
1 3 1 Take 1 from right 1
2 3 4 Take 3 from left 1, 3
3 5 4 Take 4 from right 1, 3, 4
4 5 6 Take 5 from left 1, 3, 4, 5
5 7 6 Take 6 from right 1, 3, 4, 5, 6
6 7 8 Take 7 from left 1, 3, 4, 5, 6, 7
7 — 8 Copy remainder 1, 3, 4, 5, 6, 7, 8

Seven comparisons for eight elements, matching the n − 1 bound exactly. The remainder copy in the final step is why the bound is n − 1 rather than n.

Practical actions: applying this in real code

Set a small-array cutoff. Below roughly 16 to 32 elements, swap the recursion for insertion sort and measure the crossover on your hardware; the exact threshold depends on cache size and language runtime. Use stable sort by default for any record data with a secondary sort key, and verify stability with a test that includes duplicate keys in known order. Budget the auxiliary buffer explicitly when memory is constrained; if an O(n) allocation is unacceptable, measure in-place variants against your latency target before committing. Prefer an iterative bottom-up merge for arrays large enough to approach the stack limit, since it eliminates recursion overhead entirely. For external data, sort chunks that fit in memory, write runs to disk, then merge in k-way passes; keep k modest to bound open file handles. Reconcile your thresholds in one place: cutoff size, stack depth limit, and buffer budget interact, so document all three next to the sort call.

Limitations and when merge sort is the wrong tool

Merge sort's O(n) auxiliary space disqualifies it from embedded systems with hard memory ceilings, and its lack of adaptivity makes it the wrong pick for nearly sorted streams. On modern hardware, the extra buffer traffic also hurts cache performance relative to quicksort's in-place partitioning, so a plain merge sort on an in-memory array is often 20 to 40 percent slower than a well-tuned quicksort despite the identical asymptotic bound.

The worst case is also not the whole story. Quicksort's O(n²) worst case can be triggered by adversarial inputs only if the pivot strategy is naive; randomized and median-of-three pivots make the practical risk negligible for most workloads. That means merge sort's predictability advantage matters most in graded guarantees, external sorting, and stability requirements, not in general-purpose in-memory sorting.

Finally, merge sort does not exploit key structure. For integer keys in a bounded range, counting sort or radix sort can beat it by orders of magnitude. Merge sort's proper domain is comparison-based sorting of arbitrary keys where a guaranteed bound and stable output are worth the buffer. Weigh those two requirements before choosing it; everything else is tuning.