Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created May 24, 2021 21:30
Show Gist options
  • Save helabenkhalfallah/beb0a3a7ecd056e386e6a8d705dd98b8 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/beb0a3a7ecd056e386e6a8d705dd98b8 to your computer and use it in GitHub Desktop.
Merge Sort (JS)
const merge = (arr1, arr2) => {
let sorted = [];
while (arr1.length && arr2.length) {
if (arr1[0] < arr2[0]) {
sorted.push(arr1.shift());
} else {
sorted.push(arr2.shift());
}
}
return [
...sorted,
...arr1,
...arr2
];
};
const 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);
};
const unsortedArr = [31, 99, 27, 28, 42, 13, 8, 11, 30, 17, 41, 15, 43, 1, 36, 9, 16, 20, 35, 48, 37, 7, 26, 34, 21, 22, 6, 29, 32, 49, 10, 12, 19, 24, 38, 5, 14, 44, 40, 3, 50, 46, 25, 18, 33, 47, 4, 45, 39, 23, 2];
console.log('sortedArr: ', mergeSort(unsortedArr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment