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 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.
- Divide the instance into smaller instances of the same problem.
- Conquer each smaller instance by a recursive call. When an instance is small enough (the base case), solve it directly.
- 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 to position inclusive:
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 rounds down, the left part gets elements and the right part , where 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.
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:
#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 of the subarray (the method is set out in Proving Recursive Algorithms Correct by Induction).
- Base case. If , the subarray is sorted and the procedure returns without changing it.
- Inductive step. If , both parts are strictly shorter than (their lengths are and ). By the induction hypothesis the two recursive calls leave each part sorted, holding its own original elements.
MERGEthen 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 would recurse forever. With and rounding down, that never happens.
Counting comparisons exactly
Merging a run of length with a run of length costs between comparisons (one run runs out immediately, for example when every left element is smaller) and comparisons (the runs interleave until the very end). So the worst-case number of comparisons of merge sort satisfies
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,
where means . For that is , and for it is . The program below checks the formula against the true worst case, found by running merge sort on every permutation of distinct values, and also reports the best case.
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 for :
#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, , because each merge costs at least the length of its shorter run. An already sorted array reaches it. For a power of 2 this gives , exactly half of the leading term of the worst case. Unlike insertion sort, whose best case is linear, merge sort does comparisons on every input.
The running-time recurrence
Comparisons are not the only cost: each merge also copies its elements. If is the total running time on an array of length , the three steps cost
- divide: computing , constant time;
- conquer: ;
- combine: for the merge.
So
Usually this is written loosely as . 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 . The intuition fits in one sentence: the recursion has about levels, and the merges on any one level touch each of the elements once.
Note: Merge sort pays for its guaranteed time with 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?
- Divide
- Conquer, but only in the base case
- Combine
- 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?
- 3
- 5
- 7
- 8
The worst case of merge sort satisfies . What is ?
- 48
- 49
- 64
- 33
Why must the divide step of merge sort produce two parts that are both strictly shorter than the subarray?
- So that the merge is stable
- So that the induction hypothesis applies to both recursive calls and the recursion terminates
- So that the halves have equal length
- So that the base case can be