Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting an infinite loop when I don't define the parameters?

I would like to know why I am getting an infinite loop here. I just don't want to pass this initial values, so if they are undefined they get automatically calculated. Its just to clean my function call to use only a single parameter. If I pass them everything runs ok and the process ends. Can anyone help? Thanks

function merge(array, lower, half, upper){
    //Suppressed for the sake of brevity
}

function mergeSort(array, lower, upper){
    if(!lower && !upper){ //take a look here
        lower = 0;
        upper = array.length - 1;
    }

    if(lower < upper){
        var half = Math.floor((lower + upper)/2);

        mergeSort(array, lower, half);
        mergeSort(array, half + 1, upper);
        merge(array, lower, half, upper);
    }
}

var array = [8, 3, 6, 4, 1, 0, 23, 12, 15, 63];
mergeSort(array); //infinite loop here
console.log(array);
like image 303
Renato Gama Avatar asked Jul 24 '12 15:07

Renato Gama


People also ask

How do I stop an infinite loop?

You can press Ctrl + C .

Why is my code going in infinite loop?

This is a silly example, but it's common for infinite loops to accidentally occur. Most of the times, it's because the variables used in the condition are not being updated correctly, or because the looping condition is in error. We print out x, y, and z since these variables appear in the condition.

How do you fix an infinite loop in Python?

You can stop an infinite loop with CTRL + C .

What is infinite loop explain how it can be broken through an example?

An infinite loop occurs when a condition always evaluates to true and because of this the loop control doesn't go outside of that loop. Example: i = -1. while(i != 0): print(1)


1 Answers

Your very first recursive call to mergeSort passed it 0 as first argument, because you set it so.

since !0 also evalutes to false, here you go..

Better check against undefined by using the typeof operator

if(typeof lower === 'undefined' && typeof upper === 'undefined'){ //take a look here
    lower = 0;
    upper = array.length - 1;
}

or, even better, check the arguments.length, like

if( arguments.length === 1 ) {
   var lower = 0,
       upper = array.length -1 ;
}
like image 185
jAndy Avatar answered Oct 06 '22 18:10

jAndy