Introduction
Merge sort is the standard example of divide and conquer. It splits the array into two halves, sorts each half recursively, and merges the two sorted halves in linear time. Its worst-case running time is , which matches the lower bound for comparison sorting, and it is stable. Its main cost is auxiliary memory for merging arrays. It is the usual choice for sorting linked lists and for external sorting of data that does not fit in memory.
Prerequisites
- Solving Recurrences and the Master Theorem: .
- Elementary Sorting: stability, in-place, inversions.
The merge procedure
Purpose. Combine two adjacent sorted subarrays and into one sorted subarray . Precondition. , and both subarrays are sorted.
Pseudocode uses 1-based arrays, <- for assignment and A[i..j] for the subarray from position to position .
MERGE(A, p, q, r)
L <- copy of A[p..q] // n1 = q - p + 1 elements
R <- copy of A[q+1..r] // n2 = r - q elements
i <- 1; j <- 1; k <- p
while i <= n1 and j <= n2
if L[i] <= R[j]
A[k] <- L[i]; i <- i + 1
else
A[k] <- R[j]; j <- j + 1
k <- k + 1
copy the rest of L[i..n1], then the rest of R[j..n2], into A[k..r]CLRS 3e places a sentinel at the end of and instead of testing for exhaustion; the result is the same.
Why <= matters. On a tie the element from the left half is taken first. Since left-half elements came earlier in the input, equal keys keep their order: this is what makes merge sort stable. Using < would break stability.
Cost of one merge of and elements:
- Moves: exactly (plus the copy into and ).
- Key comparisons: at least (one list runs out after all its elements are taken, each after a comparison) and at most (every output except the last needs a comparison).
- Time ; auxiliary space .
The algorithm
MERGE-SORT(A, p, r)
if p < r
q <- floor((p + r) / 2)
MERGE-SORT(A, p, q)
MERGE-SORT(A, q + 1, r)
MERGE(A, p, q, r)Initial call: MERGE-SORT(A, 1, n). A subarray of one element () is already sorted.
Worked example
Input , . The split points are for , then and , and so on. The merges happen in this order:
| Merge | Left | Right | Result | Comparisons |
|---|---|---|---|---|
| 38 | 27 | 27 38 | 1 | |
| 43 | 3 | 3 43 | 1 | |
| 27 38 | 3 43 | 3 27 38 43 | 3 | |
| 9 | 82 | 9 82 | 1 | |
| 9 82 | 10 | 9 10 82 | 2 | |
| 3 27 38 43 | 9 10 82 | 3 9 10 27 38 43 82 | 6 |
Total: 14 key comparisons. This happens to be the worst case for (formula below).


Analysis
Running time
The divide step is , the two recursive calls cost , and merging costs :
By case 2 of the master theorem, . For a power of two, the full recursion levels each do work. For general , there are levels with work per level, and full internal levels supply the matching lower bound.
The bound holds in every case. Merge sort does the same splits and the same amount of copying on every input of size ; only the number of comparisons inside the merges depends on the data.
| Case | Time | Key comparisons (exact, for the top-down version above) |
|---|---|---|
| Best | when is a power of 2 (for example, already sorted input) | |
| Worst | ||
| Average |
The worst-case formula gives 0, 1, 3, 5, 8, 11, 14 for , and when is a power of 2 (for example 17 for ).
Space
- Auxiliary arrays for merging: (at most elements are copied at any time if the buffers are freed after each merge, or one buffer of size is reused).
- Recursion stack: .
- Total auxiliary space . Standard array merge sort is therefore not in place. (In-place merging algorithms exist but are complicated and slower in practice.)
Properties
| Property | Merge sort |
|---|---|
| Time, all cases | |
| Auxiliary space | for arrays; stack only for linked lists |
| Stable | yes (take from the left half on ties) |
| In place | no (array version) |
| Adaptive | no (standard version) |
| Comparison-based | yes, and asymptotically optimal |
Variants
Bottom-up (iterative) merge sort
Treat the array as runs of length 1. Merge adjacent pairs of runs to get runs of length 2, then 4, and so on. There are passes, each , and no recursion. For : passes of run length 1, 2 and 4, so passes. The merge pattern differs from top-down merge sort when is not a power of 2, so exact comparison counts can differ.
On the worked example the array after each pass is:
| Pass | Run length merged | Array after the pass | Comparisons |
|---|---|---|---|
| 1 | 1 | 27 38 3 43 9 82 10 | 3 |
| 2 | 2 | 3 27 38 43 9 10 82 | 5 |
| 3 | 4 | 3 9 10 27 38 43 82 | 6 |
The lone 10 waits unmerged in pass 1. Here the total is also 14 comparisons, but the intermediate arrays differ from the top-down order: top-down finishes before it touches , while bottom-up treats the whole array level by level. A question about "the array after the second pass" means bottom-up.
Natural merge sort
Start from the maximal already-sorted runs of the input instead of runs of length 1. On sorted input there is one run and the sort takes time; this makes it adaptive.
Linked lists
Splitting a list (find the middle with slow and fast pointers) and merging two sorted lists need only pointer changes, so merge sort sorts a linked list in time with only the recursion stack as extra space (or bottom-up). Classic array-based heapsort needs random access and is a poor fit for lists. Quicksort can partition a linked list in linear time, but retains pivot/balance risks and is not stable in its usual form; merge sort is the natural stable choice. See Linked Lists.
-way merging and external sorting
Merging sorted lists with elements in total, using a min-heap of the current front elements, takes time. External sorting writes sorted runs to disk and then merges them in a few -way passes, so that each pass reads the data sequentially.
Small-subarray cut-off
Practical implementations switch to insertion sort for subarrays below a small size, because insertion sort has lower overhead on tiny inputs.
Applications of merging
- Counting inversions in : during a merge, when an element is output while remain, it forms inversions with them. Summing over all merges counts every inversion exactly once. For the count is 11.
- Union and intersection of two sorted lists in linear time.
- Merging two sorted arrays of sizes and : comparisons in the worst case, in the best.
- Merging several sorted lists two at a time. The order of the pairwise merges matters. For lists of sizes 20, 24, 30, 35 and 50, merging in the given order costs comparisons in the worst case. Always merging the two smallest lists first (20 with 24, 30 with 35, 44 with 50, then 65 with 94) costs , the minimum. This is the greedy optimal merge pattern, with comparisons per merge instead of moves.
Edge cases
- or : no work; the base case returns.
- All keys equal: every merge takes all of first (ties go left), using comparisons; stability is preserved.
- Odd sizes: with the left half gets the extra element.
- Overflow of in fixed-width integers: compute .
Important properties and observations
- The bound does not depend on the input order, unlike quicksort's.
- Merge sort is optimal in the comparison model up to lower-order terms: its worst case comparisons is close to .
- The number of merges is (each merge reduces the number of runs by one), and the number of calls to MERGE-SORT is .
- Merge sort is the basis of stable library sorts for objects (for example, Timsort is a natural merge sort with insertion-sort runs).
GATE examination perspective
- Comparison counts. best and worst numbers of comparisons to merge two sorted lists ( and ); the worst-case count of the whole sort for a small .
- Intermediate states. the array after a given number of merges or passes; follow the recursion order (left subtree first) for top-down, level by level for bottom-up.
- Several lists. worst-case comparisons for merging many sorted lists pairwise: merge the two smallest first, per merge.
- Recurrence questions. variants such as splitting into three parts (, still ) or merging in time ().
- Property questions. stable, not in place, in all cases, best for linked lists.
Summary
Sources
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 3rd ed., MIT Press, 2009: Section 2.3 (the divide-and-conquer approach, MERGE and MERGE-SORT, and their analysis) and Problem 2-4 (counting inversions).