Skip to content

Instantly share code, notes, and snippets.

@lostvikx
Created December 22, 2021 19:57
Show Gist options
  • Save lostvikx/9004ddad981dd6ff06ac182970d58273 to your computer and use it in GitHub Desktop.
Save lostvikx/9004ddad981dd6ff06ac182970d58273 to your computer and use it in GitHub Desktop.
// divide the list into left & right
// keep dividing until only one element is left
function mergeSort(array) {
const half = Math.floor(array.length / 2);
if (array.length < 2) {
return array;
}
let left = array.splice(0, half);
return merge(mergeSort(left), mergeSort(array));
}
// check the first elements of the two sub-arrays
// the arrays {left & right} are already sorted, we are just combining them
function merge(left, right) {
let arr = [];
// end the loop if an array gets empty
while (left.length && right.length) {
if (left[0] < right[0]) {
arr.push(left.shift());
} else {
arr.push(right.shift());
}
}
// if one array becomes empty, concatenate the remaining elements {remember the two sub-arrays are already sorted}
return [...arr, ...left, ...right];
}
console.log(mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]));
// [ 1, 1, 2, 2, 4, 8, 32, 43, 43, 55, 63, 92, 123, 123, 234, 345, 5643 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment