Just for learning and practicing I've created a completely recursive version of the merge sort algorithm.
I've tested it a little bit and it seems working, but I'm quite sure that it can be largely improved. In particular, I'm hating the long if
-else
conditional inside the sort function. I think it's really bad written but I can't figure out a way to "beautify" the code without using a loop.
function merge(left, right, array){
if (left.length == 0 && right.length == 0) {
return array;
} else if (left.length == 0) {
return array.concat(right);
} else if (right.length == 0) {
return array.concat(left);
} else if (left[0] < right[0]) {
array.push(left.shift());
} else if (left[0] > right[0]) {
array.push(right.shift());
} else {
array.push(left.shift());
right.shift();
}
return merge(left, right, array);
}
function mergeSort(array){
if (array.length > 1) {
return merge(mergeSort(array.slice(0, Math.ceil(array.length/2))),
mergeSort(array.slice(Math.ceil(array.length/2))), []);
} else {
return array;
}
}