Last active
November 2, 2017 05:58
-
-
Save leejh3224/a45e9aff74e20bf1a7efc7209820f57c 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
/* | |
* original version can be found in: | |
* https://gist.github.com/paullewis/1982121 | |
* sort(some-random-array) will return sorted array | |
*/ | |
const merge = (left, right) => { | |
const result = [] | |
while(left.length && right.length) { | |
if (left[0] < right[0]) { | |
result.push(left.shift()) | |
} else if (left[0] > right[0]){ | |
result.push(right.shift()) | |
} else { | |
result.push(left.shift()) | |
result.push(right.shift()) | |
} | |
} | |
if (left.length) { | |
return result.concat(left) | |
} | |
return result.concat(right) | |
} | |
const sort = (array) => { | |
const mid = Math.floor(array.length / 2) | |
const left = array.slice(0, mid) | |
const right = array.slice(mid) | |
if (array.length === 1) { | |
return array | |
} | |
return merge(sort(left), sort(right)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment