TExcelTAD
Home › Foundations of Algorithm Analysis › Merge Sort and the Divide-and-Conquer Pattern

Merge Sort and the Divide-and-Conquer Pattern

Insertion sort builds its answer one element at a time, and on bad inputs that costs about n2/2n^2/2 comparisons. Divide and conquer takes a different route: cut the problem into smaller copies of itself, solve the copies recursively, and stitch their answers together. Merge sort is the cleanest example of the idea, and analysing it introduces the main object of this section: the recurrence.

The DSA course's Merge Sort lesson explains the algorithm from scratch. This lesson takes it as known and concentrates on the pattern, the correctness argument and an exact count of comparisons.

Three steps: divide, conquer, combine

Every divide-and-conquer algorithm has the same shape.

  1. Divide the instance into smaller instances of the same problem.
  2. Conquer each smaller instance by a recursive call. When an instance is small enough (the base case), solve it directly.
  3. Combine the answers of the smaller instances into an answer for the original one.

For merge sort the three steps are: split the array at its middle position (divide, almost free), sort both halves recursively (conquer), and merge the two sorted halves into one sorted array (combine, where all the comparisons happen). A subarray of length 0 or 1 is already sorted, which is the base case.

In pseudocode, with 0-based indices and the subarray running from position lolo to position hihi inclusive:

text
MERGE-SORT(a, lo, hi)
1  if hi - lo < 1                    // 0 or 1 elements: nothing to do
2      return
3  mid = floor((lo + hi) / 2)
4  MERGE-SORT(a, lo, mid)            // left part:  a[lo .. mid]
5  MERGE-SORT(a, mid + 1, hi)        // right part: a[mid + 1 .. hi]
6  MERGE(a, lo, mid, hi)             // combine the two sorted runs

MERGE(a, lo, mid, hi)
1  out = empty list; i = lo; j = mid + 1
2  while i <= mid and j <= hi
3      if a[i] <= a[j]  append a[i] to out; i = i + 1
4      else             append a[j] to out; j = j + 1
5  append a[i .. mid] and then a[j .. hi] to out    // one of them is empty
6  copy out back into a[lo .. hi]

The top-level call is MERGE-SORT(a, 0, n - 1). Because midmid rounds down, the left part gets ⌈m/2⌉\lceil m/2 \rceil elements and the right part ⌊m/2⌋\lfloor m/2 \rfloor, where m=hi−lo+1m = hi - lo + 1 is the length of the subarray.

Watching the recursion

The animation runs exactly this procedure. Each merge first shows the two runs it is about to combine, then the merged result.

The Python version prints the same two lines for every merge, in the same order, and counts the comparisons made on line 3 of MERGE.

python · try it yourself
comparisons = 0

def merge_sort(a, lo, hi):
    global comparisons
    if hi - lo < 1:
        return
    mid = (lo + hi) // 2
    merge_sort(a, lo, mid)
    merge_sort(a, mid + 1, hi)
    print(f"Merge {a[lo:mid + 1]} and {a[mid + 1:hi + 1]}")
    out, i, j = [], lo, mid + 1
    while i <= mid and j <= hi:
        comparisons += 1
        if a[i] <= a[j]:
            out.append(a[i]); i += 1
        else:
            out.append(a[j]); j += 1
    out += a[i:mid + 1] + a[j:hi + 1]
    a[lo:hi + 1] = out
    print(f"  merged: {out}")

data = [38, 27, 43, 3, 9, 82, 10]
merge_sort(data, 0, len(data) - 1)
print("sorted:", data, "with", comparisons, "comparisons")
Merge [38] and [27]
  merged: [27, 38]
Merge [43] and [3]
  merged: [3, 43]
Merge [27, 38] and [3, 43]
  merged: [3, 27, 38, 43]
Merge [9] and [82]
  merged: [9, 82]
Merge [9, 82] and [10]
  merged: [9, 10, 82]
Merge [3, 27, 38, 43] and [9, 10, 82]
  merged: [3, 9, 10, 27, 38, 43, 82]
sorted: [3, 9, 10, 27, 38, 43, 82] with 14 comparisons

In C++

The same procedure in C++, with the same output:

cpp · try it yourself
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

long comparisons = 0;

// prints a[lo..hi] (both ends included) like a Python list
string show(const vector<int>& a, int lo, int hi) {
    string s = "[";
    for (int k = lo; k <= hi; k++) {
        if (k > lo) s += ", ";
        s += to_string(a[k]);
    }
    return s + "]";
}

void merge_sort(vector<int>& a, int lo, int hi) {
    if (hi - lo < 1) return;
    int mid = (lo + hi) / 2;
    merge_sort(a, lo, mid);
    merge_sort(a, mid + 1, hi);
    cout << "Merge " << show(a, lo, mid) << " and " << show(a, mid + 1, hi) << "\n";
    vector<int> out;
    int i = lo, j = mid + 1;
    while (i <= mid && j <= hi) {
        comparisons++;
        if (a[i] <= a[j]) out.push_back(a[i++]);
        else              out.push_back(a[j++]);
    }
    while (i <= mid) out.push_back(a[i++]);   // one of these two loops does nothing
    while (j <= hi) out.push_back(a[j++]);
    copy(out.begin(), out.end(), a.begin() + lo);
    cout << "  merged: " << show(out, 0, (int)out.size() - 1) << "\n";
}

int main() {
    vector<int> data = {38, 27, 43, 3, 9, 82, 10};
    merge_sort(data, 0, (int)data.size() - 1);
    cout << "sorted: " << show(data, 0, (int)data.size() - 1)
         << " with " << comparisons << " comparisons\n";
}
Merge [38] and [27]
  merged: [27, 38]
Merge [43] and [3]
  merged: [3, 43]
Merge [27, 38] and [3, 43]
  merged: [3, 27, 38, 43]
Merge [9] and [82]
  merged: [9, 82]
Merge [9, 82] and [10]
  merged: [9, 10, 82]
Merge [3, 27, 38, 43] and [9, 10, 82]
  merged: [3, 9, 10, 27, 38, 43, 82]
sorted: [3, 9, 10, 27, 38, 43, 82] with 14 comparisons

The order of the merges is the order of a post-order walk of the recursion: a merge can only happen after both of its halves are finished. The first merge is on the two leftmost single elements, and the very last merge is the one at the root, which combines the two halves of the whole array.

Why it is correct

The proof follows the shape of the algorithm, which is typical of divide and conquer. It is a strong induction on the length mm of the subarray (the method is set out in Proving Recursive Algorithms Correct by Induction).

  • Base case. If m≤1m \le 1, the subarray is sorted and the procedure returns without changing it.
  • Inductive step. If m≥2m \ge 2, both parts are strictly shorter than mm (their lengths are ⌈m/2⌉<m\lceil m/2 \rceil < m and ⌊m/2⌋≥1\lfloor m/2 \rfloor \ge 1). By the induction hypothesis the two recursive calls leave each part sorted, holding its own original elements. MERGE then turns two sorted runs into one sorted run of the same elements; that is exactly the loop-invariant proof of the merge step in Loop Invariants.

Notice what the proof needs from the divide step: that both parts are strictly smaller. A split that could return an empty part and a part of length mm would recurse forever. With m≥2m \ge 2 and rounding down, that never happens.

Counting comparisons exactly

Merging a run of length pp with a run of length qq costs between min⁡(p,q)\min(p, q) comparisons (one run runs out immediately, for example when every left element is smaller) and p+q−1p + q - 1 comparisons (the runs interleave until the very end). So the worst-case number of comparisons W(n)W(n) of merge sort satisfies

W(n)=W(⌈n/2⌉)+W(⌊n/2⌋)+n−1,W(1)=0.W(n) = W(\lceil n/2 \rceil) + W(\lfloor n/2 \rfloor) + n - 1, \qquad W(1) = 0.

This is a recurrence: an equation that defines a function in terms of its own values on smaller arguments. Solving it exactly gives a classical closed form,

W(n)=n⌈lg⁡n⌉−2⌈lg⁡n⌉+1,W(n) = n \lceil \lg n \rceil - 2^{\lceil \lg n \rceil} + 1,

where lg⁡\lg means log⁡2\log_2. For n=8n = 8 that is 8⋅3−8+1=178 \cdot 3 - 8 + 1 = 17, and for n=7n = 7 it is 7⋅3−8+1=147 \cdot 3 - 8 + 1 = 14. The program below checks the formula against the true worst case, found by running merge sort on every permutation of nn distinct values, and also reports the best case.

python · try it yourself
import itertools, math

def count(a):
    c = 0
    def sort(lo, hi):
        nonlocal c
        if hi - lo < 1:
            return
        mid = (lo + hi) // 2
        sort(lo, mid); sort(mid + 1, hi)
        out, i, j = [], lo, mid + 1
        while i <= mid and j <= hi:
            c += 1
            if a[i] <= a[j]: out.append(a[i]); i += 1
            else:            out.append(a[j]); j += 1
        a[lo:hi + 1] = out + a[i:mid + 1] + a[j:hi + 1]
    sort(0, len(a) - 1)
    return c

print(" n  worst  formula  best")
for n in range(1, 9):
    counts = [count(list(p)) for p in itertools.permutations(range(n))]
    k = math.ceil(math.log2(n))
    print(f"{n:2}  {max(counts):5}  {n * k - 2**k + 1:7}  {min(counts):4}")
 n  worst  formula  best
 1      0        0     0
 2      1        1     1
 3      3        3     2
 4      5        5     4
 5      8        8     5
 6     11       11     7
 7     14       14     9
 8     17       17    12

In C++

In C++, std::next_permutation enumerates the permutations, and std::bit_width(n - 1) is ⌈lg⁡n⌉\lceil \lg n \rceil for n≥1n \ge 1:

cpp · try it yourself
#include <algorithm>
#include <bit>
#include <cstdio>
#include <numeric>
#include <vector>
using namespace std;

// sorts a[lo..hi] and returns the number of comparisons made by the merges
long sort_count(vector<int>& a, int lo, int hi) {
    if (hi - lo < 1) return 0;
    int mid = (lo + hi) / 2;
    long c = sort_count(a, lo, mid) + sort_count(a, mid + 1, hi);
    vector<int> out;
    int i = lo, j = mid + 1;
    while (i <= mid && j <= hi) {
        c++;
        if (a[i] <= a[j]) out.push_back(a[i++]);
        else              out.push_back(a[j++]);
    }
    while (i <= mid) out.push_back(a[i++]);
    while (j <= hi) out.push_back(a[j++]);
    copy(out.begin(), out.end(), a.begin() + lo);
    return c;
}

int main() {
    printf(" n  worst  formula  best\n");
    for (int n = 1; n <= 8; n++) {
        vector<int> p(n);
        iota(p.begin(), p.end(), 0);
        long worst = 0, best = -1;
        do {
            vector<int> a = p;                 // sort a copy, keep p for next_permutation
            long c = sort_count(a, 0, n - 1);
            worst = max(worst, c);
            best = best < 0 ? c : min(best, c);
        } while (next_permutation(p.begin(), p.end()));
        int k = bit_width(unsigned(n - 1));    // ceil(lg n) for n >= 1
        printf("%2d  %5ld  %7d  %4ld\n", n, worst, n * k - (1 << k) + 1, best);
    }
}
 n  worst  formula  best
 1      0        0     0
 2      1        1     1
 3      3        3     2
 4      5        5     4
 5      8        8     5
 6     11       11     7
 7     14       14     9
 8     17       17    12

The best case follows its own recurrence, B(n)=B(⌈n/2⌉)+B(⌊n/2⌋)+⌊n/2⌋B(n) = B(\lceil n/2 \rceil) + B(\lfloor n/2 \rfloor) + \lfloor n/2 \rfloor, because each merge costs at least the length of its shorter run. An already sorted array reaches it. For nn a power of 2 this gives B(n)=n2lg⁡nB(n) = \frac{n}{2} \lg n, exactly half of the leading term of the worst case. Unlike insertion sort, whose best case is linear, merge sort does Θ(nlg⁡n)\Theta(n \lg n) comparisons on every input.

The running-time recurrence

Comparisons are not the only cost: each merge also copies its mm elements. If T(n)T(n) is the total running time on an array of length nn, the three steps cost

  • divide: computing midmid, constant time;
  • conquer: T(⌈n/2⌉)+T(⌊n/2⌋)T(\lceil n/2 \rceil) + T(\lfloor n/2 \rfloor);
  • combine: Θ(n)\Theta(n) for the merge.

So

T(n)={Θ(1)if n≤1,T(⌈n/2⌉)+T(⌊n/2⌋)+Θ(n)if n≥2.T(n) = \begin{cases} \Theta(1) & \text{if } n \le 1, \\ T(\lceil n/2 \rceil) + T(\lfloor n/2 \rfloor) + \Theta(n) & \text{if } n \ge 2. \end{cases}

Usually this is written loosely as T(n)=2T(n/2)+Θ(n)T(n) = 2T(n/2) + \Theta(n). The next lessons show how to set up such equations (Writing Recurrences) and three ways to solve them: substitution, recursion trees and the master theorem. All three give T(n)=Θ(nlg⁡n)T(n) = \Theta(n \lg n). The intuition fits in one sentence: the recursion has about lg⁡n\lg n levels, and the merges on any one level touch each of the nn elements once.

Note: Merge sort pays for its guaranteed Θ(nlg⁡n)\Theta(n \lg n) time with Θ(n)\Theta(n) extra memory for the merge buffer. Library sorts such as Python's Timsort keep the merging idea but first look for runs that are already sorted, which makes them linear on nearly sorted data.

Test yourself

In merge sort, which of the three divide-and-conquer steps performs all of the element comparisons?

  1. Divide
  2. Conquer, but only in the base case
  3. Combine
  4. None: merge sort compares only indices

How many comparisons does merging a sorted run of length 5 with a sorted run of length 3 need in the worst case?

  1. 3
  2. 5
  3. 7
  4. 8

The worst case of merge sort satisfies W(n)=n⌈lg⁡n⌉−2⌈lg⁡n⌉+1W(n) = n \lceil \lg n \rceil - 2^{\lceil \lg n \rceil} + 1. What is W(16)W(16)?

  1. 48
  2. 49
  3. 64
  4. 33

Why must the divide step of merge sort produce two parts that are both strictly shorter than the subarray?

  1. So that the merge is stable
  2. So that the induction hypothesis applies to both recursive calls and the recursion terminates
  3. So that the halves have equal length
  4. So that the base case can be n=2n = 2