This post shows how to implement Merge Sort in JavaScript — an efficient, divide-and-conquer sorting algorithm and one of the most commonly asked "implement a sort from scratch" interview questions.
Merge sort in JavaScript:
Explanation:
Merge sort works by repeatedly splitting the array in half until each piece has just one element, then merging those pieces back together in sorted order. The merge step compares the smallest remaining elements of each half and builds the sorted result one element at a time. This gives merge sort a reliable O(n log n) time complexity, even in the worst case — unlike simpler sorts like bubble sort.
See Merge Sort in Action
Drag the slider to scrub through every comparison and write, or use Play to watch the divide-and-conquer merge process run automatically.
JavaScript Program to Implement Merge Sort
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(left, right) {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result.push(left[i]);
i++;
} else {
result.push(right[j]);
j++;
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
const numbers = [38, 27, 43, 3, 9, 82, 10];
console.log("Sorted array:", mergeSort(numbers));
Output:
Sorted array: [ 3, 9, 10, 27, 38, 43, 82 ]
Merge sort's divide-and-conquer approach shows up constantly in interviews — practice more algorithm problems in our Interview Prep section, or run and modify this code in our Code Runner.
Frequently Asked Questions About Merge Sort in JavaScript
What is the time complexity of merge sort?
Merge sort runs in O(n log n) time in the best, average, and worst case, because the array is always split in half (log n splits) and each merge step takes O(n) time.
Is merge sort better than bubble sort?
For larger datasets, yes. Merge sort's O(n log n) complexity is far faster than bubble sort's O(n²) for large inputs, though merge sort does use extra memory for the temporary arrays created during merging.
Is merge sort a stable sorting algorithm?
Yes. Merge sort preserves the relative order of equal elements, which matters when sorting objects by one field while needing to preserve their original order for ties.
