Skip to content

Instantly share code, notes, and snippets.

@klochner
Created July 17, 2015 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klochner/4065b67034d50fbc3b02 to your computer and use it in GitHub Desktop.
Save klochner/4065b67034d50fbc3b02 to your computer and use it in GitHub Desktop.
function merge(ray1, ray2) {
var out = [];
var index1 = 0;
var index2 = 0;
var length1 = ray1.length;
var length2 = ray2.length;
while (index1 < length1 && index2 < length2) {
var item1 = ray1[index1];
var item2 = ray2[index2];
if (item1 <= item2) {
out.push(item1);
++index1;
} else {
out.push(item2);
++index2;
}
}
return out.concat(index1 < length1
? ray1.slice(index1, length1)
: ray2.slice(index2, length2)
);
}
function mergesort(arr) {
return arr.length <= 1
? arr
: merge(mergesort(arr.slice(0, arr.length / 2)),
mergesort(arr.slice(arr.length / 2, arr.length)));
};
console.log(mergesort([]))
console.log(mergesort([1]))
console.log(mergesort([2, 1]))
console.log(mergesort([3, 2, 1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment