Merge Sort is a highly efficient, stable sorting algorithm that follows the divide-and-conquer strategy. It works by recursively breaking down an unsorted list into smaller sublists until each sublist contains only one element (which is inherently sorted). Then, it repeatedly merges these sorted sublists to produce a final sorted list.
Let's consider the unsorted list: [8, 3, 1, 7, 0, 10, 2]
1. Divide:
[8, 3, 1, 7]
and [0, 10, 2]
.2. Conquer:
[8, 3, 1, 7]
becomes [1, 3, 7, 8]
.[0, 10, 2]
becomes [0, 2, 10]
.3. Combine:
[1, 3, 7, 8]
and [0, 2, 10]
to produce [0, 1, 2, 3, 7, 8, 10]
.function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const mid = Math.floor(arr.length / 2);
const leftArr = mergeSort(arr.slice(0, mid));
const rightArr = mergeSort(arr.slice(mid));
return merge(leftArr, rightArr);
}
function merge(leftArr, rightArr) {
let resultArr = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < leftArr.length && rightIndex < rightArr.length) {
if (leftArr[leftIndex] < rightArr[rightIndex]) {
resultArr.push(leftArr[leftIndex]);
leftIndex++;
} else {
resultArr.push(rightArr[rightIndex]);
rightIndex++;
}
}
// Add remaining elements from left or right array
while (leftIndex < leftArr.length) {
resultArr.push(leftArr[leftIndex]);
leftIndex++;
}
while (rightIndex < rightArr.length) {
resultArr.push(rightArr[rightIndex]);
rightIndex++;
}
return resultArr;
}
Merge Sort is a highly efficient sorting algorithm that shines due to its consistent time complexity and stable nature. While it requires additional space, its overall performance makes it a valuable sorting tool for many applications.