I have a class in which a binary search is implemented.
import java.util.Arrays;
import java.util.Random;
public class BinarySearch {
public static boolean search(int[] array, int value) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int index = (right + left) / 2;
if (array[index] == value)
return true;
if (array[index] < value)
right = index - 1;
else
left = index + 1;
}
return false;
}
public static void main(String[] arg) {
int[] array = {1,2,3,4,5,6,7,8};
int value = 4 ;
if (search(array,value))
System.out.println("The value " + value + " is in the array.");
else {
System.out.println("The value " + value + " is not in the array.");
}
}
}
The problem is, when I replace the value of 4 in the main method, it will always print out e.g. The value 8 is not in the array.
However, I can't find the bug in the search method. Can anybody of you see it? I tried using a debugger, but it still doesn't help me.