I am working through intro to algorithms and translating the pseudocode into a variety of languages for practice.
I am stuck on javascript. I cannot figure out why my merge function is failing and duplicating inputs. Do you know why?
Thank you
function mergesort(a){
if (a.length <=1) {
return a;
}
mid = Math.round((a.length/2));
left = a.slice(0, mid);
right = a.slice(mid);
console.log(left,right);
return merge(mergesort(left), mergesort(right));
}
function merge(left, right) {
sorted = [];
console.log(sorted,left, right, left[0], right[0]);
while (left && left.length >0 && right && right.length >0){
if (left[0] <= right[0]) {
sorted.push(left.shift());
console.log("left", left, right);
}
else {
sorted.push(right.shift());
console.log("left", left, right);
}
}
return sorted.concat(left,right);
}
a = [234,526,6,3,2,5];
mergesort(a);
sortedvariable, right?mergesortare global. Global variables and recursion don't generally mix.var sortedto prevent creating globals. All variables are global by default in JS if you omit thevarkeyword.