Created
March 28, 2016 15:55
-
-
Save thm-design/32e60d8fc0070e8563ad to your computer and use it in GitHub Desktop.
Merge Sort Algorithm
This file contains hidden or 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
/* | |
Merge Sort | |
*/ | |
const mergeSort = (nums) => { | |
if (nums.length < 2) return nums; | |
const length = nums.length; | |
const middle = Math.floor(length / 2); | |
const left = nums.slice(0, middle); | |
const right = nums.slice(middle, length); | |
return merge(mergeSort(left), mergeSort(right)); | |
}; | |
const merge = (left, right) => { | |
const results = []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) results.push(left.shift()); | |
else results.push(right.shift()); | |
} | |
while(left.length) results.push(left.shift()); | |
while(right.length) results.push(right.shift()); | |
return results; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment