-
-
Save abenteuerzeit/e5dd100167b396428f3805cc8c0f4d14 to your computer and use it in GitHub Desktop.
Merge Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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