I just finished studying the simple BinarySearch algorithm, but one thing that bugs me is that I was taught that break (and continue) statements are often redundant in Java and you can do with most while-loops without them. But I can't figure out how to get rid of hem from the BinarySearch while-loop below:-
public static void BinarySearch(int[] list, int key){
int lo = 0;
int hi = list.length-1;
int mid = 0;
while(lo<=hi){
mid = lo + (hi-lo) / 2;
if(key<list[mid])
hi = mid-1;
else if(key>list[mid])
lo = mid+1;
else {
System.out.println("Key is found at index = " + mid);
break;
}
if(lo>hi){
System.out.println("Key doesn't exist in the list");
}
}
Question 1: Why does the loop keeps going on and on if I didn't include the break statement? Shouldn't the variable "lo" eventually become greater than "hi"? How come the last if- conditional can see that, but not the while-loop-conditional?
Question 2: How can I can type the while-loop without needing the break statement?