Home > other >  while I'm getting infinite while loop in java
while I'm getting infinite while loop in java

Time:04-28

I want to write a code which loops in a 2d array, the main method is findVal which gets a 2d array and a value and return true if the value is in the array, I used a binary search code to loop through a single row of the array and another method which goes down in rows in the 2d array, the problem is when I run a tester it doen't open the terminal window and it looks like my loop is infinite, my code is the following

public static int linearSearch(int [] arr, int num)
    {
        int pos=0;
        while ((arr[pos]<num)&&(pos<arr.length-1))
            pos  ;
        if(arr[pos]==num){return pos;}
        else {return -1;}
    }
public static boolean findVal(int [][] m, int val)
    {
        int n=m.length;
        int j=m.length-1, i=0;
        while (i<=j)
        {
            if(val == m[i][j]){return true;}
            
            else if(val > m[i][j] ){

                if(linearSearch(m[i],val) !=-1){return true;}

            }
            else{
                i  ;
            }

        }

        return false;
    }

can someone tell me what I'm doing wrong? Note: I can't use nested loops neither run through n*n in a for loop.

CodePudding user response:

Your while body has an if-else if-else structure with three branches. The first uses a return statement to exit the method, so that won't cause an infinite loop. The third increments i so that should eventually cause the loop to end. It's the second one that's the issue. It contains a conditional return statement. However, if that condition is not met, the loop body does nothing. That means that the loop condition won't change, and the same branch is chosen every time.

CodePudding user response:

Your else if condition is causing the loop to go infinite.

 else if(val > m[i][j] ){

                if(linearSearch(m[i],val) !=-1){return true;}

            }

In case -1 is returned from the linearSearch(m[i],val) . You are not increasing i or j which in turn is causing the same values of i and j to be evaluated again and again in the while loop.

Try to do a i in case the value from linearSearch(m[i],val) == -1 that will fix the issue of infinite loop

  • Related