简体   繁体   中英

Binary Search won't ever finish, I have to terminate it myself

public static boolean binarySearch(int[] data, int value){
    int start = 0; 
    int end = data.length-1;
    int middle = (start + end) / 2;
        while(end >= start){
            if(data[middle] == value){
                System.out.println("binarySearch found value " + value + " at position " + data[middle]);
                return true;
            }
            if(data[middle] < value){
                start = middle + 1; 
            }
            if(data[middle] > value){
                end = middle + 1; 
            }
        }
        return false;
}

I have this code for binary search, and to me it looks like everything is in check. But when i pass an array and a variable I'm looking for through it it doesn't give me anything in return and I just have to terminate it. Any thoughts?

 if(data[middle] == value)

this part checks if the middle of the array equals to data all the time . If you don't modify the variable middle , no matter what you do, it will always check if the middle value is equal to data .

Since you don't modify start and end as well,

 while(end >= start)

this part also prevents you to finish the loop.

This is what I tried:

int data[] = {1, 3, 4, 5, 7, 8, 12};
int value = 7;
binarySearch(data, value);

And this is the output I get when I add

 System.out.println("Start: " + start +
 " Middle: " + middle + " End: " + end);

at the beginning of while loop:

Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
...

to infinity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM