Created
November 10, 2018 18:42
-
-
Save cefaijustin/c5c9790347019b91a9e5c45421338da2 to your computer and use it in GitHub Desktop.
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 = (arr) => { | |
if (arr.length < 2) return arr; | |
const middle = Math.floor(arr.length / 2); | |
const left = arr.slice(0, middle); | |
const right = arr.slice(middle); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
const merge = (left, right) => { | |
const result = []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) { | |
result.push(left.shift()) | |
} else { | |
result.push(right.shift()) | |
} | |
} | |
return result.concat(left, right); | |
} | |
console.log(mergeSort([4, 2, 7, 1, 3, 5, 9])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment