Created
July 17, 2015 20:18
-
-
Save klochner/4065b67034d50fbc3b02 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
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