Skip to content

Instantly share code, notes, and snippets.

@eengineergz
Created February 27, 2021 05:13
Show Gist options
  • Save eengineergz/cbb533137a7f957d3bc4077395c1ff64 to your computer and use it in GitHub Desktop.
Save eengineergz/cbb533137a7f957d3bc4077395c1ff64 to your computer and use it in GitHub Desktop.
function merge(arr1, arr2) {
let result = [];
while (arr1.length && arr2.length) {
if (arr1[0] < arr2[0]) {
result.push(arr1.shift());
} else {
result.push(arr2.shift());
}
}
return [...result, ...arr1, ...arr2];
}
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment