Overview
Data Structures
Searching
Merge Sort is a divide-and-conquer algorithm that splits the array into halves, sorts them recursively, and then merges the sorted halves to form the final sorted array.
It has a time complexity of O(n log n) and is much more efficient than Bubble Sort for large datasets.
// Merge Sort in JavaScript
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++]);
} else {
result.push(right[j++]);
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
console.log(mergeSort([4, 2, 7, 1, 9, 3])); // Output: [1, 2, 3, 4, 7, 9]Start with an empty array of a chosen length. New slots start as NULL — fill them with Push or Insert below.
Splits the array recursively, then merges the smaller sorted parts back together.
Merge Sort is used in scenarios where large datasets need to be sorted efficiently. It's especially useful in external sorting, where data doesn't fit into memory.
A practical example is sorting millions of search results quickly or processing large log files in cloud services.
// Simulating sorting of large dataset const logs = [542, 112, 998, 400, 213, 675, 100]; console.log(mergeSort(logs)); // Output: [100, 112, 213, 400, 542, 675, 998]