Merge sort
Merge sort splits the array in two, sorts each half recursively, and merges the two sorted halves in O(n); with log₂ n levels it is always O(n log n), stable, and needs a second O(n) array.
Bubble, selection and insertion sort are O(n²): a million numbers take hundreds of billions of comparisons. Merge sort starts from another fact: merging two already sorted arrays into one sorted array takes only O(n). So split the array in two, sort each half, and merge; each half can be split the same way.
Merging: two sorted into one
Each side has a pointer, i and j. Compare the two current numbers, put the smaller into the temporary array tmp, and move that side's pointer on. When one side runs out, copy what's left of the other.
i↑j↑kEach number placed costs at most one comparison, so merging n numbers is O(n).
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)
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.
1#include <stdio.h>2 3int tmp[6];4 5void merge(int a[], 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(void) {16 int a[] = {1, 4, 7, 2, 3, 9};17 merge(a, 0, 2, 5);18 for (int i = 0; i < 6; i++)19 printf("%d ", a[i]);20 printf("\n");21 return 0;22}
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 last stage of this lesson shows.
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 <stdio.h>2 3int tmp[6];4 5void merge(int a[], 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(void) {16 int a[] = {1, 4, 7, 2, 3, 9};17 merge(a, 0, 2, 5);18 for (int i = 0; i < 6; i++)19 printf("%d ", a[i]);20 printf("\n");21 return 0;22}
mid, a[mid] would count in both halves and tmp would overflow; with lo or hi, some numbers get repeated or lost.Write merge
✓Finish merge: merge the sorted a[lo..mid] and a[mid+1..hi] and copy the result back into a.
1 2 3 5 8 9 10
1#include <stdio.h>2 3int tmp[10];4 5void merge(int a[], int lo, int mid, int hi) {6 int i = lo, j = mid + 1, k = lo;7 // while both have some, take the smaller; then copy the rest; then back into a8}9 10int main(void) {11 int a[] = {2, 5, 8, 1, 3, 9, 10};12 merge(a, 0, 2, 6);13 for (int i = 0; i < 7; i++)14 printf("%d ", a[i]);15 printf("\n");16 return 0;17}
Split, sort, merge
merge_sort(a, lo, hi) sorts a[lo..hi]: one number needs no sorting; otherwise split at the middle, mid, sort each side recursively, and merge.
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:
You call merge_sort(a, 0, 5) on 6 numbers. Which two parts does the first split make?
The recursion
merge_sort(a, 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:
1#include <stdio.h>2 3int tmp[8];4 5void merge(int a[], 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(int a[], int lo, int hi) {16 if (lo >= hi) return;17 int mid = (lo + hi) / 2;18 merge_sort(a, lo, mid);19 merge_sort(a, mid + 1, hi);20 merge(a, lo, mid, hi);21}22 23int main(void) {24 int a[] = {8, 3, 5, 1, 7, 2};25 merge_sort(a, 0, 5);26 for (int i = 0; i < 6; i++)27 printf("%d ", a[i]);28 printf("\n");29 return 0;30}
1 2 3 5 7 8
Watch the call stack in the picture: merge_sort calls pile up, at most log₂ n deep, and each one merges as it returns.
For 8 numbers, how many times is merge_sort called?
1#include <stdio.h>2 3int calls = 0;4 5void merge_sort(int lo, int hi) {6 calls++;7 if (lo >= hi) return;8 int mid = (lo + hi) / 2;9 merge_sort(lo, mid);10 merge_sort(mid + 1, hi);11}12 13int main(void) {14 merge_sort(0, 7);15 printf("%d\n", calls);16 return 0;17}
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.
merge_sort(a, mid + 1, hi);int mid = (lo + hi) / 2;merge_sort(a, lo, mid);if (lo >= hi) return;merge(a, lo, mid, hi);
1 2 3 5 7 8
Write merge_sort
✓merge is given. Finish the recursion: split in two, sort each, merge.
1 2 4 6 7 8 9
1#include <stdio.h>2 3int tmp[10];4 5void merge(int a[], 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(int a[], int lo, int hi) {16 // one number: return; otherwise split at mid, recurse on both sides, merge17}18 19int main(void) {20 int a[] = {9, 4, 7, 1, 8, 2, 6};21 merge_sort(a, 0, 6);22 for (int i = 0; i < 7; i++)23 printf("%d ", a[i]);24 printf("\n");25 return 0;26}
Why O(n log n)
The easiest way to count merge sort's work is level by level.
Each level of merging handles n numbers in total, and there are about log₂ n levels, so it's O(n log n). For a million numbers n² is 10¹² and n log n 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.
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?
You give merge sort an array that is already sorted. How long does it take?
The price: a second array
Merging can't write straight into the original array (it would overwrite numbers not yet compared), so it needs a tmp as big as the array: O(n) extra space. That is the big difference from quicksort.
| Time (best / average / worst) | Extra space | Stable | |
|---|---|---|---|
| Merge sort | O(n log n) for all three | O(n) | stable |
Its time is always O(n log n), with no bad case; it's stable; and it suits linked lists (merging lists needs no extra array) and external sorting (data too big for memory, sorted in chunks and then merged).
Stability comes from the <= in merge: on a tie it takes the left one, and the left one was in front to begin with, so equal numbers never swap order.
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 <stdio.h>2 3typedef struct {4 int score;5 char name;6} Item;7 8Item a[] = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};9Item tmp[4];10 11void merge(int lo, int mid, int hi) {12 int i = lo, j = mid + 1, k = lo;13 while (i <= mid && j <= hi) {14 if (a[i].score a[j].score) tmp[k++] = a[i++];15 else tmp[k++] = a[j++];16 }17 while (i <= mid) tmp[k++] = a[i++];18 while (j <= hi) tmp[k++] = a[j++];19 for (k = lo; k <= hi; k++)20 a[k] = tmp[k];21}22 23void merge_sort(int lo, int hi) {24 if (lo >= hi) return;25 int mid = (lo + hi) / 2;26 merge_sort(lo, mid);27 merge_sort(mid + 1, hi);28 merge(lo, mid, hi);29}30 31int main(void) {32 merge_sort(0, 3);33 for (int i = 0; i < 4; i++)34 printf("%d%c ", a[i].score, a[i].name);35 printf("\n");36 return 0;37}
1B 1D 2A 2C
<, a tie takes the right side first: when 1B and 1D are merged, D jumps ahead of B and the order flips. With <=, a tie takes the left side first, and the sort is stable.What is the biggest cost of merge sort?
Summary
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; stable (the left one first on a tie)
1if (lo >= hi) return;2mid = (lo + hi) / 2;3merge_sort(a, lo, mid);4merge_sort(a, mid + 1, hi);5merge(a, lo, mid, hi);