Created
November 10, 2018 01:36
-
-
Save cefaijustin/9132ba54631e14f36ec594446c7c2cd3 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
mergeSort = (arr) => { | |
if (arr.length < 2) return arr; | |
var middle = Math.floor(arr.length / 2); | |
var left = arr.slice(0, middle); | |
var right = arr.slice(middle, arr.length); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
merge = (left, right) => { | |
var result = []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) { | |
result.push(left.shift()); | |
} else { | |
result.push(right.shift()); | |
} | |
} | |
while (left.length) result.push(left.shift()); | |
while (right.length) result.push(right.shift()); | |
return result; | |
} | |
console.log(mergeSort([3, 1, 6, 2, 7])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment