Created
February 9, 2019 11:01
-
-
Save imsarvesh/c600c98b56fa0ade53dca5d34a34decf 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
function mergeSort(array) { | |
if(array.length < 2) return array; | |
var middle = Math.floor(array.length / 2); | |
var left = array.slice(0, middle); | |
var right = array.slice(middle); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
function merge(left, right) { | |
var sorted = []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) { | |
sorted.push(left.shift()); | |
} else { | |
sorted.push(right.shift()); | |
} | |
} | |
return [...sorted, ...left, ...right]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment