Skip to content
Codescope

Merge sort

Divide, sort halves, merge — stable and reliably O(n log n).

core11 min8 steps

Before you start

Merge sort is built on one observation: **merging two already-sorted lists is easy**. Look at the front of each, take the smaller, repeat. One pass, linear time.

So the algorithm cheats. It splits the array in half, sorts each half (by calling itself), and then merges the two sorted halves. The splitting bottoms out at single elements, which are sorted by definition — nothing to do.

Unlike quicksort, merge sort makes no bet on the input: it is O(n log n) on every array, sorted or shuffled or reversed. The price is that the merge step needs a scratch buffer, so it uses O(n) extra memory.

merge sort

7 values, unsorted
input
38
27
43
3
9
82
10

No comparisons yet. First the array gets taken apart.

Step 1 of 8. An unsorted array. Eight values, no order. Merge sort will not compare distant elements or shuffle things around in place — it works strictly by splitting and recombining. The whole algorithm is the two halves of one idea: **split until trivial, then merge back up**.

01 / 08

Step 01 / 08

An unsorted array

Eight values, no order. Merge sort will not compare distant elements or shuffle things around in place — it works strictly by splitting and recombining.

The whole algorithm is the two halves of one idea: **split until trivial, then merge back up**.

merge-sort.cC
void merge_sort(int a[], int lo, int hi) {    if (hi - lo < 2) return;          /* 0 or 1 element: sorted */    int mid = lo + (hi - lo) / 2;    merge_sort(a, lo,  mid);          /* sort left half  */    merge_sort(a, mid, hi);           /* sort right half */    merge(a, lo, mid, hi);            /* combine them    */}void merge(int a[], int lo, int mid, int hi) {    int tmp[hi - lo], i = lo, j = mid, k = 0;    while (i < mid && j < hi)         /* take the smaller head */        tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++];    while (i < mid)  tmp[k++] = a[i++];   /* drain left  */    while (j < hi)   tmp[k++] = a[j++];   /* drain right */    for (int x = 0; x < k; x++) a[lo + x] = tmp[x];}