Skip to content

Instantly share code, notes, and snippets.

@abenteuerzeit
Forked from codecademydev/index.js
Created August 17, 2023 13:21
Show Gist options
  • Save abenteuerzeit/e5dd100167b396428f3805cc8c0f4d14 to your computer and use it in GitHub Desktop.
Save abenteuerzeit/e5dd100167b396428f3805cc8c0f4d14 to your computer and use it in GitHub Desktop.
Merge Sort
const mergeSort = (startArray) => {
const length = startArray.length;
if (length === 1) {
return startArray;
}
const mid = Math.floor(length / 2);
const leftArray = startArray.slice(0, mid);
const rightArray = startArray.slice(mid, length);
return merge(mergeSort(leftArray), mergeSort(rightArray));
};
const merge = (leftArray, rightArray) => {
const sortedArray = [];
while (leftArray.length > 0 && rightArray.length > 0) {
if (leftArray[0] < rightArray[0]) {
sortedArray.push(leftArray.shift());
} else {
sortedArray.push(rightArray.shift());
}
}
return sortedArray.concat(leftArray).concat(rightArray);
};
const inputArr = [3, 5, 2, 90, 4, 7];
console.log(mergeSort(inputArr));
module.exports = {
mergeSort,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment