Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my Binary search stuck in an endless loop?

I just had to pop in here to hopefully get a quick answer to my little problem. I’m trying to create a binary search method but ran into some problems. I created it iteratively, which my IDE(Intellij) apparently didn’t like. It had me stuck in a endless loop of… well, you know the rest. Any suggestions?

Here is my simple, yet beautiful little snippet of code:

static int searchIt(int[] arr, int target){    
    int left = 0;                              
    int right = arr.length - 1;                
    while (left <= right){                     
        int mid = (right + left) / 2;          
        if(arr[mid] == target) {               
            return mid;                        
        } else if(target < arr[mid]){          
            right = mid-1;                     
        } else{                                
            left = mid -1;                     
        }                                      
    }                                          
    return -1;                                 
}                                              

No errors, not in runtime or compile time, just endless nothingness…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

left value should be mid + 1 since if the your middle your target value greater than your mid value then you need to search the element in second half of your array

static int searchIt(int[] arr, int target){    
    int left = 0;                              
    int right = arr.length - 1;                
    while (left <= right){                     
        int mid = (right + left) / 2;          
        if(arr[mid] == target) {               
            return mid;                        
        } else if(target < arr[mid]){          
            right = mid - 1;                     
        } else{                                
            left = mid + 1;                     
        }                                      
    }                                          
    return -1;                                 
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading