Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created August 17, 2023 13:21
Show Gist options
  • Save codecademydev/7ba544fb051337af98a39cccd978ac39 to your computer and use it in GitHub Desktop.
Save codecademydev/7ba544fb051337af98a39cccd978ac39 to your computer and use it in GitHub Desktop.
Codecademy export
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