Last active
December 22, 2015 00:45
-
-
Save tuscen/a2f432be9c46505e6d0c to your computer and use it in GitHub Desktop.
Functional merge sort in JS
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
| 'use strict'; | |
| var mergesort = (function () { | |
| "use strict"; | |
| function sort(array) { | |
| if (array.length < 2) { | |
| return array; | |
| } | |
| const length = array.length | |
| , mid = Math.floor(length * 0.5) | |
| , left = array.slice(0, mid) | |
| , right = array.slice(mid, length); | |
| return merge(sort(left), sort(right)); | |
| } | |
| function merge(left, right) { | |
| function iter(current, other, acc) { | |
| if (current.length === 0) { | |
| return acc.concat(other); | |
| } else if(other.length === 0) { | |
| return acc.concat(current); | |
| } | |
| const [newCurrent, newOther] = current[0] <= other[0] ? | |
| [current, other] : [other, current]; | |
| return iter(newCurrent.slice(1), newOther, acc.concat([newCurrent[0]])); | |
| }; | |
| return iter(left, right, []); | |
| } | |
| return { | |
| sort: sort | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment