Merge sort is a highly efficient sorting algorithm known for its stability and predictable performance. It operates on the principle of "divide and conquer", recursively breaking down an array into smaller subarrays until each subarray contains only one element (which is inherently sorted). These sorted subarrays are then merged back together in a sorted manner.
Let's consider an unsorted array:
[8, 3, 1, 7, 0, 10, 2]
Step 1: Divide
The array is divided into two halves:
[8, 3, 1, 7] [0, 10, 2]
Step 2: Conquer
The process is recursively repeated on each half until we reach single-element arrays, which are inherently sorted.
Step 3: Combine
The sorted subarrays are merged back together:
function mergeSort(array) {
if (array.length <= 1) {
return array;
}
const middle = Math.floor(array.length / 2);
const left = mergeSort(array.slice(0, middle));
const right = mergeSort(array.slice(middle));
return merge(left, right);
}
function merge(left, right) {
const result = [];
let i = 0;
let 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++;
}
}
while (i < left.length) {
result.push(left[i]);
i++;
}
while (j < right.length) {
result.push(right[j]);
j++;
}
return result;
}