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);
You can press Ctrl + C .
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.
You can stop an infinite loop with CTRL + C .
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)
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 ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With