algorithms · high
Merge Sort
Merge sort divides the array down to single elements then merges sorted runs back together. It is O(n log n) in the best, average, and worst case and is stable, at the cost of O(n) auxiliary space for merging. Because it accesses data sequentially, it's the standard choice for linked lists and for external (on-disk) sorting.
Merge sort recursively splits then merges sorted halves; guaranteed O(n log n) in all cases and stable, but uses O(n) extra space. The go-to for linked lists and external sorting.
The code
void merge(int a[], int lo, int mid, int hi); // merge two sorted halves
void mergeSort(int a[], int lo, int hi) { if (lo >= hi) return; // 0 or 1 element: sorted int mid = lo + (hi - lo) / 2; mergeSort(a, lo, mid); // sort the left half mergeSort(a, mid + 1, hi); // sort the right half merge(a, lo, mid, hi); // merge them back together}What this lesson walks through
- 01Merge sort — divide and conquer
- 02Merge runs of width 1
- 03Merge runs of width 2
- 04Merge runs of width 4
- 05Sorted
Merge sort splits the array down to single elements (each trivially sorted), then merges sorted runs back together. Shown bottom-up: merge runs of width 1, then 2, then 4.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Merge Sort and 100+ animated C++ interview lessons.