Kodewick
Start learning →
Merge sort43 / 52

Merge sort

Lesson 43 of 52 · Part 8 · Sorting · about 24 minutes

Merge sort splits the array in two, sorts each half recursively and merges them in O(n), so it is always O(n log n); it needs a temporary array, it is stable, and std::stable_sort uses it.

Bubble, selection and insertion sort are all O(n²): a million numbers take hundreds of billions of comparisons. Merge sort starts from a different idea: merging two already sorted arrays into one sorted array takes only O(n). So cut the array in half, sort each half, and merge them; each half can be cut the same way. It's what runs inside std::stable_sort.

Merging: two sorted runs into one

Each side has an index, i and j. Compare the current values of the two sides, put the smaller into the temporary array tmp, and move that side's index on. When one side runs out, the rest of the other is copied over as is.

a's left half, right half, and tmpleftrighttmp14723901234567891011↑i↑j↑k

Merging 1 4 7 and 2 3 9: compare the front of each side, the smaller goes into tmp

Each value placed costs at most one comparison, so merging n values is O(n).

Choose one

Merging 1 4 7 and 2 3 9: which side does each of the 6 numbers put into tmp come from, in order? (L = left half, R = right half)

Choose one

How many comparisons does it take to merge 2 5 8 and 1 3 9 10?

merge in C++

Writing merge in C++ takes three indexes: i walks the left half a[lo..mid], j walks the right half a[mid+1..hi], and k is the next free place in tmp. A merge has three steps: while both sides have numbers, take the smaller; copy whatever is left on either side; then copy tmp back into a. a and tmp are both passed by reference (vector<int>&): nothing is copied, and merge changes the two arrays themselves.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void merge(vector<int>& a, vector<int>& tmp, int lo, int mid, int hi) {6    int i = lo, j = mid + 1, k = lo;7    while (i <= mid && j <= hi)8        tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];9    while (i <= mid) tmp[k++] = a[i++];10    while (j <= hi) tmp[k++] = a[j++];11    for (k = lo; k <= hi; k++)12        a[k] = tmp[k];13}14 15int main() {16    vector<int> a = {1, 4, 7, 2, 3, 9};17    vector<int> tmp(a.size());18    merge(a, tmp, 0, 2, 5);19    for (int x : a)20        cout << x << " ";21    cout << "\n";22    return 0;23}
Output
1 2 3 4 7 9 

The comparison is <=: when the two sides are equal, the left one goes first. That is what makes merge sort stable, as the stage on its cost shows.

Fill inTap one to fill a blank; tap a blank to take it back

At which index does the right half start? Fill in the blank so merge combines 1 4 7 and 2 3 9 correctly.

1#include <iostream>2#include <vector>3using namespace std;4 5void merge(vector<int>& a, vector<int>& tmp, int lo, int mid, int hi) {6    int i = lo, j = , k = lo;7    while (i <= mid && j <= hi)8        tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];9    while (i <= mid) tmp[k++] = a[i++];10    while (j <= hi) tmp[k++] = a[j++];11    for (k = lo; k <= hi; k++)12        a[k] = tmp[k];13}14 15int main() {16    vector<int> a = {1, 4, 7, 2, 3, 9};17    vector<int> tmp(a.size());18    merge(a, tmp, 0, 2, 5);19    for (int x : a)20        cout << x << " ";21    cout << "\n";22    return 0;23}
Exercise 1

Write merge

Fill in merge: merge the sorted a[lo..mid] and a[mid+1..hi] into tmp, then copy back into a.

It should print
1 2 3 5 8 9 10
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void merge(vector<int>& a, vector<int>& tmp, int lo, int mid, int hi) {6    int i = lo, j = mid + 1, k = lo;7    // take the smaller while both sides have values; then copy the rest; then copy back into a8}9 10int main() {11    vector<int> a = {2, 5, 8, 1, 3, 9, 10};12    vector<int> tmp(a.size());13    merge(a, tmp, 0, 2, 6);14    for (int x : a)15        cout << x << " ";16    cout << "\n";17    return 0;18}
Output
Press Run or Ctrl+Enter

Split, sort, merge

merge_sort(a, tmp, lo, hi) sorts a[lo..hi]: a single value needs no sorting; otherwise split at the middle, mid, sort each side recursively, then merge.

Merge sort on 8 3 5 1 7 2: the top three levels split in two each time until each piece is a single value (amber); the bottom three merge in pairs, each merge sorted (green), until one whole sorted array is left. log₂ n levels of splitting, log₂ n of merging

The recursion works in a fixed order: it splits the left half all the way down and merges it first, then comes back for the right half. Here it is step by step on four numbers, 8 3 5 1:

8 3 5 1
1void merge_sort(vector<int>& a, vector<int>& tmp, int lo, int hi) {2    if (lo >= hi) return;3    int mid = (lo + hi) / 2;4    merge_sort(a, tmp, lo, mid);5    merge_sort(a, tmp, mid + 1, hi);6    merge(a, tmp, lo, mid, hi);7}

merge_sort on 8 3 5 1: the left half is split all the way down first and merged on the way back; only then is it the right half's turn
Choose one

You call merge_sort(a, tmp, 0, 5) on 6 numbers. Which two parts does the first split make?

The recursion

merge_sort(a, tmp, lo, hi) itself is just a few lines: with one number (or none) it returns straight away; otherwise it works out mid, calls itself once on each half, and merges once both halves are sorted. You can run the whole program step by step, with the array drawn as bars and the call stack beside it:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void merge(vector<int>& a, vector<int>& tmp, int lo, int mid, int hi) {6    int i = lo, j = mid + 1, k = lo;7    while (i <= mid && j <= hi)8        tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];9    while (i <= mid) tmp[k++] = a[i++];10    while (j <= hi) tmp[k++] = a[j++];11    for (k = lo; k <= hi; k++)12        a[k] = tmp[k];13}14 15void merge_sort(vector<int>& a, vector<int>& tmp, int lo, int hi) {16    if (lo >= hi) return;17    int mid = (lo + hi) / 2;18    merge_sort(a, tmp, lo, mid);19    merge_sort(a, tmp, mid + 1, hi);20    merge(a, tmp, lo, mid, hi);21}22 23int main() {24    vector<int> a = {8, 3, 5, 1, 7, 2};25    vector<int> tmp(a.size());          // the temporary array, made once26    merge_sort(a, tmp, 0, a.size() - 1);27    for (int x : a)28        cout << x << " ";29    cout << "\n";30    return 0;31}
Output
1 2 3 5 7 8 

The temporary array tmp is made once in main and passed down by reference: making a new vector in every merge call would add millions of memory allocations.

Watch the call stack in the picture: merge_sort calls pile up, at most log₂ n deep, and each one merges as it returns.

Guess the outputA wrong guess is fine

With 8 values, how many times is merge_sort called in all?

1#include <iostream>2using namespace std;3 4int calls = 0;5 6void merge_sort(int lo, int hi) {7    calls++;8    if (lo >= hi) return;9    int mid = (lo + hi) / 2;10    merge_sort(lo, mid);11    merge_sort(mid + 1, hi);12}13 14int main() {15    merge_sort(0, 7);16    cout << calls << "\n";17    return 0;18}
Put in orderDrag, or use the arrows

Put the 5 lines of merge_sort in order so the program sorts 8 3 5 1 7 2 into 1 2 3 5 7 8.

  1. merge_sort(a, tmp, mid + 1, hi);
  2. int mid = (lo + hi) / 2;
  3. merge_sort(a, tmp, lo, mid);
  4. if (lo >= hi) return;
  5. merge(a, tmp, lo, mid, hi);
Should print
1 2 3 5 7 8
Exercise 2

Write merge_sort

merge is given. Fill in the recursion: split in two, sort each half, then merge.

It should print
1 2 4 6 7 8 9
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void merge(vector<int>& a, vector<int>& tmp, int lo, int mid, int hi) {6    int i = lo, j = mid + 1, k = lo;7    while (i <= mid && j <= hi)8        tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];9    while (i <= mid) tmp[k++] = a[i++];10    while (j <= hi) tmp[k++] = a[j++];11    for (k = lo; k <= hi; k++)12        a[k] = tmp[k];13}14 15void merge_sort(vector<int>& a, vector<int>& tmp, int lo, int hi) {16    // return on a single value; otherwise split at mid, recurse on both sides, then merge17}18 19int main() {20    vector<int> a = {9, 4, 7, 1, 8, 2, 6};21    vector<int> tmp(a.size());22    merge_sort(a, tmp, 0, a.size() - 1);23    for (int x : a)24        cout << x << " ";25    cout << "\n";26    return 0;27}
Output
Press Run or Ctrl+Enter

Why O(n log n)

The easiest way to count merge sort's work is level by level.

The merges on each level handle exactly n values between them, and there are about log₂ n levels, so the total is O(n log n). For a million numbers, n² is 10¹² while n log n is only 2 × 10⁷: fifty thousand times faster.

In exams: two-way merge sort takes ⌈log₂ n⌉ passes; after pass k, every run of 2ᵏ is sorted.

Choose one

Two-way merge sort on 6 2 8 4 1 7 3 5: pass 1 merges in twos, pass 2 in fours. What does the array look like after pass 2?

Choose one

You give merge sort an array that is already sorted. How long does it take?

The cost: a temporary array

A merge can't write into the array it's reading from (it would overwrite values not yet compared), so it needs a tmp as big as the array: O(n) extra space. That's the biggest difference between merge sort and quicksort.

Time (best / average / worst)Extra spaceStable
Merge sortO(n log n) for allO(n), plus O(log n) of recursion stackstable

Its time is always O(n log n), with no bad worst case; it's stable (with a[i] <= a[j] the left one goes first, so equal values keep their order; write < and it's no longer stable); it suits linked lists (merging lists only changes pointers, no extra array) and external sorting (data too big for memory, sorted in chunks and then merged).

Change it

Each person has a score and a name, sorted by score from low to high. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before D).

1#include <iostream>2#include <vector>3using namespace std;4 5struct Item {6    int score;7    char name;8};9 10vector<Item> a = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};11vector<Item> tmp(4);12 13void merge(int lo, int mid, int hi) {14    int i = lo, j = mid + 1, k = lo;15    while (i <= mid && j <= hi) {16        if (a[i].score  a[j].score) tmp[k++] = a[i++];17        else tmp[k++] = a[j++];18    }19    while (i <= mid) tmp[k++] = a[i++];20    while (j <= hi) tmp[k++] = a[j++];21    for (k = lo; k <= hi; k++)22        a[k] = tmp[k];23}24 25void merge_sort(int lo, int hi) {26    if (lo >= hi) return;27    int mid = (lo + hi) / 2;28    merge_sort(lo, mid);29    merge_sort(mid + 1, hi);30    merge(lo, mid, hi);31}32 33int main() {34    merge_sort(0, 3);35    for (auto& p : a)36        cout << p.score << p.name << " ";37    cout << "\n";38    return 0;39}
Should print
1B 1D 2A 2C

With the STL

The STL has four things built on merging:

  • stable_sort(b, e, comp): a stable sort, merge sort inside. libstdc++ first tries to get a buffer (at most n/2 elements) to merge with, O(n log n); if it can't, it falls back to merging in place without a buffer, a bit slower, O(n log² n).
  • merge(b1, e1, b2, e2, out): merges two sorted ranges and writes them to out, the same merge as in the "merge in C++" stage, O(n). The output needs room for them first.
  • inplace_merge(b, m, e): [b, m) and [m, e) are each sorted; it merges them into one range, left where it was. O(n) with a buffer.
  • list::sort(): std::list can't jump to an index, so std::sort doesn't work on it; its own sort is merge sort on the list, changing only pointers, and stable.
main.cpp
1#include <iostream>2#include <vector>3#include <list>4#include <string>5#include <algorithm>6#include <functional>7using namespace std;8 9// merge sort written with std::merge, sorting [lo, hi)10void msort(vector<int>& a, vector<int>& tmp, int lo, int hi) {11    if (hi - lo < 2) return;12    int mid = (lo + hi) / 2;13    msort(a, tmp, lo, mid);14    msort(a, tmp, mid, hi);15    merge(a.begin() + lo, a.begin() + mid, a.begin() + mid, a.begin() + hi, tmp.begin() + lo);16    copy(tmp.begin() + lo, tmp.begin() + hi, a.begin() + lo);   // copy back into a17}18 19int main() {20    vector<int> x = {1, 4, 7}, y = {2, 3, 9};21    vector<int> z(x.size() + y.size());               // make room first22    merge(x.begin(), x.end(), y.begin(), y.end(), z.begin());23    cout << "merge: ";24    for (int v : z) cout << v << " ";25    cout << "\n";26 27    vector<int> a = {8, 3, 5, 1, 7, 2};28    vector<int> tmp(a.size());29    msort(a, tmp, 0, a.size());30    cout << "msort: ";31    for (int v : a) cout << v << " ";32    cout << "\n";33 34    vector<string> w = {"pear", "fig", "apple", "kiwi", "plum", "date"};35    stable_sort(w.begin(), w.end(), [](const string& p, const string& q) {36        return p.size() < q.size();                   // by length only37    });38    cout << "stable_sort: ";39    for (auto& s : w) cout << s << " ";40    cout << "\n";41 42    list<int> l = {5, 2, 8, 1, 9};43    l.sort(greater<int>());                           // the list's merge sort, largest first44    cout << "list::sort: ";45    for (int v : l) cout << v << " ";46    cout << "\n";47    return 0;48}
Output
merge: 1 2 3 4 7 9 
msort: 1 2 3 5 7 8 
stable_sort: fig pear kiwi plum date apple 
list::sort: 9 8 5 2 1 

The two lines in msort that merge and copy back could also be the single line inplace_merge(a.begin() + lo, a.begin() + mid, a.begin() + hi);, with no tmp of your own: it gets its own buffer.

stable_sort compares by length only, and pear kiwi plum date, all of length 4, keep their old order. merge, inplace_merge and stable_sort all take a comparator too, with the same rule as sort: true when x goes before y, strict < only.

CallWhat it doesTimeExtra space
sort(b, e)introsort, not stableO(n log n)O(log n)
stable_sort(b, e)merge sort, stableO(n log n); O(n log² n) without a bufferup to O(n)
merge(b1, e1, b2, e2, out)two sorted ranges merged elsewhereO(n)the output range
inplace_merge(b, m, e)two adjacent sorted ranges merged in placeO(n); O(n log n) without a bufferup to O(n)
l.sort() (std::list)merge sort on a list, stableO(n log n)O(1), pointers only

In interviews: "sort versus stable_sort": the first is introsort, not stable, with almost no extra memory; the second is merge sort, stable, with an O(n) buffer. The merging idea comes back in "merge two / k sorted lists", "sort a linked list" (O(n log n) wanted: use merge sort) and "count the inversions in an array" (when a value from the right goes out first during a merge, it forms an inversion with every value left on the left).

Guess the outputA wrong guess is fine

Four people sorted by score (on a tie, look at the original order). What does the program print?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<pair<int, char>> v = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};8    stable_sort(v.begin(), v.end(), [](const pair<int, char>& p, const pair<int, char>& q) {9        return p.first < q.first;10    });11    for (auto& p : v)12        cout << p.first << p.second << " ";13    cout << "\n";14    return 0;15}

Summary

Take-away

Merge sort: split in two, sort, merge

  • merge: two sorted runs, compare their fronts, the smaller first, O(n)
  • log₂ n levels of O(n) each: always O(n log n)
  • Needs an O(n) temporary array (made once, passed by reference); stable (the left one first on a tie)
  • STL: stable_sort is merge sort; merge writes elsewhere, inplace_merge merges in place; a list uses l.sort()
1if (lo >= hi) return;2int mid = (lo + hi) / 2;3merge_sort(a, tmp, lo, mid);4merge_sort(a, tmp, mid + 1, hi);5merge(a, tmp, lo, mid, hi);