Last active
August 29, 2015 14:22
-
-
Save xypaul/f7d7942bfa6f376e1a8f to your computer and use it in GitHub Desktop.
Merge Sort JavaScript
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 sort(array) { | |
var len = array.length; | |
var middle = Math.floor(len*0.5); | |
var left = array.slice(0,middle); | |
var right = array.slice(middle, len); | |
if (len == 1) { | |
return array; | |
} else { | |
} | |
return merge(sort(left), sort(right)); | |
} | |
function merge(left, right) { | |
var a = left.length; | |
var b = right.length; | |
if (a > 0 && b > 0) { | |
if (left[0] > right[0]) { | |
return [].concat(left[0], merge(left.slice(1,a), right)); | |
} else { | |
return [].concat(right[0], merge(right.slice(1,b), left)); | |
} | |
} else if (a == 0) { | |
return right; | |
} else of (b == 0) | |
return left; | |
} | |
var array = []; | |
for(var i = 0; i < 20; i++) { | |
array.push(Math.round(Math.random() * 100)); | |
} | |
console.log(array); | |
console.log(sort(array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This one is using too much recursion in the merge function - http://codereview.stackexchange.com/questions/92020/beginner-implementation-of-merge-sort/92038#92038