Binary search doesn't return the correct index in an array
I tried for hours, but I can't understand why my search doesn't bring back the right value. Somehow it skips the bold code in the last iteration. I know I could just copy someones else's code entirely, but I wanted to find the mistake in my code.
public class binarysearch {
public static int findvalue(int arr[], int value) {
int left = 0;
int right = arr.length - 1;
int middle = (right + left) / 2;
while (value != arr[middle]) {
if (value > arr[middle]) {
left = middle;
middle = (left + right) / 2;
} else if (value < arr[middle]) {
right = middle;
middle = (left + right) / 2;
} else {
return -1;
}
break;
}
return middle;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
int value = 9;
int indexFromArry = findvalue(arr, value);
int valueFromArry = arr[indexFromArry];
System.out.println("index is: " + indexFromArry);
if ((indexFromArry >= 0) && (indexFromArry < arr.length)) {
System.out.println("value searched by index is: " + valueFromArry);
}
}
}
Solution 1:
I think it would execute that statement given the chance, but you are breaking out of the while
loop too soon.
Specifically, you have an unnecessary break
statement immediately after the else {return -1;}
. That break
statement stops the search after the first binary cut, so get rid of it.
Offhand, i think there are further issues with your algorithm, that might lead to infinite loops - eg if the search value is not present, etc. So compare your code against other references - eg even https://en.m.wikipedia.org/wiki/Binary_search_algorithm will do for this (*)
(*) apologies to any Wikipedia proponents !