function mergeSort(array: number[], low: number, high: number) {if (high - low < 1) return;
const middle = (low + high) >> 1;
mergeSort(array, low, middle);
mergeSort(array, middle + 1, high);
const merged: number[] = [];
let i = low, j = middle + 1;
while (i <= middle && j <= high) {if (array[i] <= array[j]) merged.push(array[i++]);
else merged.push(array[j++]);
}
while (i <= middle) merged.push(array[i++]);
while (j <= high) merged.push(array[j++]);
for (let k = 0; k < merged.length; k++) array[low + k] = merged[k];
}
Start: 24 values. mergeSort(a, 0, 23) splits until the ranges have one element, then merges.
Understanding Merge sort
The idea
Merge sort splits the range in half, sorts each half recursively, and merges the two sorted halves by repeatedly taking the smaller front element. Ranges of one element are sorted by definition, so the recursion bottoms out immediately and all the work happens in the merges.
Every level of the recursion merges n elements in total, and there are log₂ n levels, so the cost is n log n whatever the input. The price is the buffer: merging in place is possible but awkward, so the textbook version copies into a temporary array and back.
The four stages
Complexity
Versus its siblings
Pseudocode
MERGESORT(array, low, high)
if high − low < 1: return
middle ← ⌊(low + high) / 2⌋
MERGESORT(array, low, middle); MERGESORT(array, middle + 1, high)
merge the sorted halves into merged, smaller front first
copy merged back into array[low..high]
When to use
Pitfalls
History
John von Neumann wrote merge sort in 1945 as one of the first programs for the EDVAC, and described it formally with Herman Goldstine in 1948. It is the ancestor of Tim sort, which Tim Peters built for Python in 2002 and which Java and Android adopted later.