Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Created May 2, 2016 22:35
Show Gist options
  • Save jonahwilliams/d732257dffcf6f8549dbaa4c59fdba25 to your computer and use it in GitHub Desktop.
Save jonahwilliams/d732257dffcf6f8549dbaa4c59fdba25 to your computer and use it in GitHub Desktop.
mergesort
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