/**
* merge(left, right)
* -------------------
* Merges two **sorted** arrays into one sorted array.
* This version uses shift(), which removes the first element of an array.
*/
function merge(left, right) {
let arr = []; // final merged result
// Continue while both arrays still have elements
while (left.length && right.length) {
// Compare the first elements of each array
if (left[0] < right[0]) {
arr.push(left.shift()); // take from left
} else {
arr.push(right.shift()); // take from right
}
}
// One of the arrays may still have leftover elements.
// Spread syntax appends whatever remains.
return [...arr, ...left, ...right];
}
/**
* mergeSort(arr)
* ----------------
* Recursively splits the array into halves, sorts each half,
* and merges them back together.
*
* NOTE: This version mutates the array using splice().
*/
function mergeSort(arr, halflength = arr.length / 2) {
// Base case: arrays with fewer than 2 elements are already sorted
if (arr.length < 2) {
return arr;
}
// Remove the first half of the array and store it in "left"
const left = arr.splice(0, halflength);
// Recursively sort the left half and the remaining right half
return merge(mergeSort(left), mergeSort(arr));
}
let arr = [10, 8, 5, 4, 3, 6, 2, 7, 1, 9];
console.log(mergeSort(arr));
/*
Explanation:
------------
This implementation of merge sort works in three phases:
1. DIVIDE:
mergeSort() splits the array into two halves using splice().
It keeps splitting until each subarray has only one element.
2. CONQUER:
Each half is sorted recursively.
3. COMBINE:
The merge() function compares the first elements of each sorted half
and builds a new sorted array by repeatedly taking the smaller value.
run:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*/