Merge sort (recursion)
Medium TimeO(n log n) SpaceO(n)
Given an array arr of numbers, return a new array holding the same values in ascending order, sorted by splitting the array in half and merging the sorted halves back together. The input is left exactly as it was, and an array of 0 or 1 values is already sorted.
Examples
Example 1
- Input
- arr = [5, 2, 8, 1, 9, 3]
- Output
- The same six values, ascending:
[1,2,3,5,8,9]1, 2, 3, 5, 8, 9.
Example 2
- Input
- arr = [4, 1, 4]
- Output
- Both 4s come back — sorting rearranges, it does not remove.
[1,4,4]
The Code
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) out.push(a[i++]);
else out.push(b[j++]);
}
return out.concat(a.slice(i)).concat(b.slice(j));
}
mergeSort([5, 2, 8, 1, 9, 3]);Done
The first 21 calls, of 31. This one does not fit on a page.
More like this
All sorting examples (8) →- Quick sort Pick a pivot, partition around it, recurse on each side.
- Bubble sort Repeatedly swap adjacent out-of-order pairs until sorted.
- Insertion sort Grow a sorted prefix, inserting each new item into place.
- Selection sort Find the smallest remaining element and swap it into place.
- Counting sort No comparisons — tally each value, then read the tallies back out.
- Heap sort Build a max-heap, then repeatedly move the root to the back.