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 Θ(nlg⁡n)\Theta(n \lg n), which matches the lower bound for comparison sorting, and it is stable. Its main cost is Θ(n)\Theta(n) 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

The merge procedure

Purpose. Combine two adjacent sorted subarrays A[p..q]A[p..q] and A[q+1..r]A[q+1..r] into one sorted subarray A[p..r]A[p..r]. Precondition. p≤q<rp \le q < r, and both subarrays are sorted.

Pseudocode uses 1-based arrays, <- for assignment and A[i..j] for the subarray from position ii to position jj.

Text
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 ∞\infty at the end of LL and RR 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 n1n_1 and n2n_2 elements:

  • Moves: exactly n1+n2n_1 + n_2 (plus the copy into LL and RR).
  • Key comparisons: at least min⁡(n1,n2)\min(n_1, n_2) (one list runs out after all its elements are taken, each after a comparison) and at most n1+n2−1n_1 + n_2 - 1 (every output except the last needs a comparison).
  • Time Θ(n1+n2)\Theta(n_1 + n_2); auxiliary space Θ(n1+n2)\Theta(n_1 + n_2).

The algorithm

Text
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 (p=rp = r) is already sorted.

Worked example

Input A=[38,27,43,3,9,82,10]A = [38, 27, 43, 3, 9, 82, 10], n=7n = 7. The split points are q=4q = 4 for [1..7][1..7], then q=2q = 2 and q=6q = 6, and so on. The merges happen in this order:

MergeLeftRightResultComparisons
A[1..2]A[1..2]382727 381
A[3..4]A[3..4]4333 431
A[1..4]A[1..4]27 383 433 27 38 433
A[5..6]A[5..6]9829 821
A[5..7]A[5..7]9 82109 10 822
A[1..7]A[1..7]3 27 38 439 10 823 9 10 27 38 43 826

Total: 14 key comparisons. This happens to be the worst case for n=7n = 7 (formula below).

Merge sort split and merge tree
Figure 1. Merge sort on 38 27 43 3 9 82 10: the top half splits the array down to single elements; the bottom half merges them back, each merged block labelled with its comparison count.
The final merge step by step
Figure 2. The final merge of 3 27 38 43 with 9 10 82: pointers ii and jj, the element output at each of the 6 comparisons, and the leftover 82 copied without comparison.

Analysis

Running time

The divide step is Θ(1)\Theta(1), the two recursive calls cost 2T(n/2)2T(n/2), and merging costs Θ(n)\Theta(n):

T(n)=2T(n/2)+Θ(n),T(1)=Θ(1).T(n) = 2T(n/2) + \Theta(n), \qquad T(1) = \Theta(1).

By case 2 of the master theorem, T(n)=Θ(nlg⁡n)T(n) = \Theta(n \lg n). For nn a power of two, the full recursion levels each do Θ(n)\Theta(n) work. For general nn, there are O(lg⁡n)O(\lg n) levels with O(n)O(n) work per level, and Θ(lg⁡n)\Theta(\lg n) 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 nn; only the number of comparisons inside the merges depends on the data.

CaseTimeKey comparisons (exact, for the top-down version above)
BestΘ(nlg⁡n)\Theta(n \lg n)n2lg⁡n\tfrac{n}{2} \lg n when nn is a power of 2 (for example, already sorted input)
WorstΘ(nlg⁡n)\Theta(n \lg n)n⌈lg⁡n⌉−2⌈lg⁡n⌉+1n \lceil \lg n \rceil - 2^{\lceil \lg n \rceil} + 1
AverageΘ(nlg⁡n)\Theta(n \lg n)nlg⁡n−Θ(n)n \lg n - \Theta(n)

The worst-case formula gives 0, 1, 3, 5, 8, 11, 14 for n=1,…,7n = 1, \ldots, 7, and nlg⁡n−n+1n \lg n - n + 1 when nn is a power of 2 (for example 17 for n=8n = 8).

Space

  • Auxiliary arrays for merging: Θ(n)\Theta(n) (at most nn elements are copied at any time if the buffers are freed after each merge, or one buffer of size nn is reused).
  • Recursion stack: Θ(lg⁡n)\Theta(\lg n).
  • Total auxiliary space Θ(n)\Theta(n). Standard array merge sort is therefore not in place. (In-place merging algorithms exist but are complicated and slower in practice.)

Properties

PropertyMerge sort
Time, all casesΘ(nlg⁡n)\Theta(n \lg n)
Auxiliary spaceΘ(n)\Theta(n) for arrays; Θ(lg⁡n)\Theta(\lg n) stack only for linked lists
Stableyes (take from the left half on ties)
In placeno (array version)
Adaptiveno (standard version)
Comparison-basedyes, and asymptotically optimal

Variants

Bottom-up (iterative) merge sort

Treat the array as nn runs of length 1. Merge adjacent pairs of runs to get runs of length 2, then 4, and so on. There are ⌈lg⁡n⌉\lceil \lg n \rceil passes, each Θ(n)\Theta(n), and no recursion. For n=7n = 7: passes of run length 1, 2 and 4, so ⌈lg⁡7⌉=3\lceil \lg 7 \rceil = 3 passes. The merge pattern differs from top-down merge sort when nn is not a power of 2, so exact comparison counts can differ.

On the worked example the array after each pass is:

PassRun length mergedArray after the passComparisons
1127 38 3 43 9 82 103
223 27 38 43 9 10 825
343 9 10 27 38 43 826

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 A[1..4]A[1..4] before it touches A[5..7]A[5..7], 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 Θ(n)\Theta(n) 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 Θ(nlg⁡n)\Theta(n \lg n) time with only the Θ(lg⁡n)\Theta(\lg n) recursion stack as extra space (or O(1)O(1) 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.

kk-way merging and external sorting

Merging kk sorted lists with nn elements in total, using a min-heap of the kk current front elements, takes O(nlg⁡(k+1))O(n \lg(k+1)) time. External sorting writes sorted runs to disk and then merges them in a few kk-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 Θ(nlg⁡n)\Theta(n \lg n): during a merge, when an element R[j]R[j] is output while L[i..n1]L[i..n_1] remain, it forms n1−i+1n_1 - i + 1 inversions with them. Summing over all merges counts every inversion exactly once. For [38,27,43,3,9,82,10][38, 27, 43, 3, 9, 82, 10] the count is 11.
  • Union and intersection of two sorted lists in linear time.
  • Merging two sorted arrays of sizes mm and nn: m+n−1m + n - 1 comparisons in the worst case, min⁡(m,n)\min(m, n) 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 (20+24−1)+(44+30−1)+(74+35−1)+(109+50−1)=382(20 + 24 - 1) + (44 + 30 - 1) + (74 + 35 - 1) + (109 + 50 - 1) = 382 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 43+64+93+158=35843 + 64 + 93 + 158 = 358, the minimum. This is the greedy optimal merge pattern, with a+b−1a + b - 1 comparisons per merge instead of a+ba + b moves.

Edge cases

  • n=0n = 0 or n=1n = 1: no work; the base case p≥rp \ge r returns.
  • All keys equal: every merge takes all of LL first (ties go left), using n1n_1 comparisons; stability is preserved.
  • Odd sizes: with q=⌊(p+r)/2⌋q = \lfloor (p + r)/2 \rfloor the left half gets the extra element.
  • Overflow of p+rp + r in fixed-width integers: compute q=p+⌊(r−p)/2⌋q = p + \lfloor (r - p)/2 \rfloor.

Important properties and observations

  • The Θ(nlg⁡n)\Theta(n \lg n) 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 nlg⁡n−Θ(n)n \lg n - \Theta(n) comparisons is close to lg⁡(n!)≈nlg⁡n−1.44n\lg(n!) \approx n \lg n - 1.44n.
  • The number of merges is n−1n - 1 (each merge reduces the number of runs by one), and the number of calls to MERGE-SORT is 2n−12n - 1.
  • 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 (min⁡(m,n)\min(m, n) and m+n−1m + n - 1); the worst-case count of the whole sort for a small nn.
  • 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, a+b−1a + b - 1 per merge.
  • Recurrence questions. variants such as splitting into three parts (3T(n/3)+Θ(n)3T(n/3) + \Theta(n), still Θ(nlg⁡n)\Theta(n \lg n)) or merging in Θ(n2)\Theta(n^2) time (2T(n/2)+Θ(n2)=Θ(n2)2T(n/2) + \Theta(n^2) = \Theta(n^2)).
  • Property questions. stable, not in place, Θ(nlg⁡n)\Theta(n \lg n) in all cases, best for linked lists.

Summary

Sources

  1. 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).

Next steps