data-structures · intermediate · ~30 min

Merge sort

Recursive divide-and-conquer; the merge step on two sorted runs.

Challenge

Implement void merge_sort(int *a, size_t n) that sorts a in non-decreasing order. You may allocate a scratch buffer with malloc.

Why this matters

Merge sort is the canonical divide-and-conquer algorithm and the basis for sorting linked lists, external sorts on huge files, and stable sorts in most language standard libraries.

Input format

Array a of n ints (n <= 100000).

Output format

a is sorted in place.

Constraints

No qsort. O(n log n) time, O(n) auxiliary memory.

Starter code

#include <stddef.h>
#include <stdlib.h>
void merge_sort(int *a, size_t n) { /* TODO */ }

Common mistakes

Off-by-one when copying the right half back; forgetting to free the scratch buffer; merging in-place naively (which is O(n^2)).

Edge cases to handle

n==0 and n==1 must early-return without allocating. Already-sorted and reverse-sorted inputs.

Complexity

Time O(n log n) worst case. Space O(n) for the scratch buffer.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.