This is my first time implementing a merge sort (just getting started with algorithms & data structures).
Are there any obvious things I have done wrong?
I am also worried that I have overused recursion, as both the merge & the sort function are recursive.
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));
From the feedback in this question, I have improved my solution, which can be found here.