Created
May 2, 2016 22:35
-
-
Save jonahwilliams/d732257dffcf6f8549dbaa4c59fdba25 to your computer and use it in GitHub Desktop.
mergesort
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
function mergesort(xs) { | |
if (xs.length < 2) { | |
return xs | |
} | |
const n = xs.length / 2 | 0; | |
return merge(mergesort(xs.slice(0, n)), mergesort(xs.slice(n))); | |
} | |
function merge(xs, ys) { | |
const result = []; | |
while (xs.length > 0 || ys.length > 0) { | |
if (xs.length === 0) { | |
return result.concat(ys); | |
} | |
if (ys.length === 0) { | |
return result.concat(xs); | |
} | |
if(xs[0] < ys[0]) { | |
result.push(xs.shift()); | |
} else { | |
result.push(ys.shift()); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment