Merge sort is a classic divide and conquer algorithm: split the array in half, sort each half, then merge the two sorted halves into one. Because the array is halved again and again, merge sort always runs in O(n log n) time, even in the worst case. It is stable and is the natural choice for sorting linked lists and very large files.
In this lesson you will learn
- The divide and conquer idea
- How to merge two sorted arrays
- A complete merge sort in C
- Watching the recursion split and merge
- Why its complexity is O(n log n)
Merge Sort in C
#include <stdio.h>
#include <stdlib.h>
/* Merge two sorted halves a[lo..mid] and a[mid+1..hi] */
void merge(int a[], int lo, int mid, int hi, int tmp[]) {
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi)
tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++]; /* <= keeps it stable */
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = lo; k <= hi; k++) a[k] = tmp[k];
}
void merge_sort(int a[], int lo, int hi, int tmp[]) {
if (lo >= hi) return; /* 0 or 1 element: already sorted */
int mid = lo + (hi - lo) / 2;
merge_sort(a, lo, mid, tmp); /* sort left half */
merge_sort(a, mid + 1, hi, tmp); /* sort right half */
merge(a, lo, mid, hi, tmp); /* combine */
}
int main(void) {
int a[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof a / sizeof a[0];
int *tmp = malloc(n * sizeof *tmp);
if (tmp == NULL) return 1;
merge_sort(a, 0, n - 1, tmp);
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
free(tmp);
return 0;
}
Output
3 9 10 27 38 43 82
- Divide:
merge_sortfinds the middle and calls itself on each half. The base case is a range of 0 or 1 elements, which is already sorted. - Conquer: the two recursive calls return sorted halves.
- Combine:
mergewalks both halves with two indexes, always copying the smaller front value intotmp, then copies any leftovers and writes the result back. mid = lo + (hi - lo) / 2avoids the integer overflow that(lo + hi) / 2can cause with very large indexes.- Taking from the left half when values are equal (
<=) keeps equal elements in their original order, so merge sort is stable.
Watching It Work
#include <stdio.h>
/* Show how merge sort splits and merges, with indentation per level */
void show(const int a[], int lo, int hi) {
printf("[");
for (int i = lo; i <= hi; i++) printf("%d%s", a[i], i < hi ? " " : "");
printf("]");
}
void merge_sort(int a[], int lo, int hi, int depth) {
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
merge_sort(a, lo, mid, depth + 1);
merge_sort(a, mid + 1, hi, depth + 1);
int tmp[16], i = lo, j = mid + 1, k = 0;
while (i <= mid && j <= hi) tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (int t = 0; t < k; t++) a[lo + t] = tmp[t];
printf("%*smerged ", depth * 2, "");
show(a, lo, hi);
printf("\n");
}
int main(void) {
int a[] = {38, 27, 43, 3, 9, 82, 10};
merge_sort(a, 0, 6, 0);
return 0;
}
Output
merged [27 38]
merged [3 43]
merged [3 27 38 43]
merged [9 82]
merged [9 10 82]
merged [3 9 10 27 38 43 82]
Indentation shows the depth of recursion. The smallest pieces are merged first, deep inside the recursion, and each level merges larger and larger sorted runs until the top level merges the two halves of the whole array.
Why O(n log n)?
Halving an array of n elements until the pieces have size 1 takes about log₂ n levels. At every level, the merges together touch each of the n elements once. So the total work is n × log₂ n. For 1,000,000 items that is about 20 million steps, compared with about a trillion for an O(n²) sort.
| Property | Merge sort |
|---|---|
| Time (best, average, worst) | O(n log n) |
| Extra space | O(n) for the temporary array |
| Stable | Yes |
| Recurrence | T(n) = 2T(n/2) + O(n) |
The main cost is the extra O(n) memory. Quick sort avoids it and is often faster on arrays in practice, but it has a worse worst case. For linked lists, merge sort needs no extra array, because nodes can be relinked.
Common Mistakes
- Allocating a new temporary array inside every merge call, which is slow. Allocate once and pass it down, as above.
- Forgetting to copy the leftovers from one half after the other runs out.
- Wrong split points, such as sorting
lo..mid-1andmid..hiinconsistently, causing infinite recursion. - Forgetting to
freethe temporary buffer.
Practice Exercises
Exercise 1. Write a function that merges two sorted arrays of sizes m and n into a third array.
Show answer
void merge_two(const int a[], int m, const int b[], int n, int out[]) {
int i = 0, j = 0, k = 0;
while (i < m && j < n) out[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
while (i < m) out[k++] = a[i++];
while (j < n) out[k++] = b[j++];
}
Exercise 2. How many levels of splitting does merge sort need for 1,024 elements?
Show answer
log₂ 1024 = 10 levels.
Frequently Asked Questions
Is merge sort better than quick sort?
Merge sort guarantees O(n log n) and is stable; quick sort usually runs faster on arrays and needs less memory but can degrade to O(n²). Many languages use merge-sort-based algorithms (such as Timsort) when stability is required.
What is external sorting?
Sorting data too big for memory. Chunks are sorted in memory, written to disk, then merged together, which is exactly merge sort’s merge step at a large scale.
Summary
- Merge sort splits, sorts each half recursively and merges.
- It is O(n log n) in every case and stable.
- It needs O(n) extra memory for arrays.
- Merging two sorted sequences is a useful technique on its own.
Next: Quick Sort in C.
