我有一个实现二进制搜索的类。
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.");
}
}
}
问题是,当我在main method
中替换值4时,它将始终打印出来,例如The value 8 is not in the array.
但是,我无法在search
方法中找到错误。你们有人能看到吗?我尝试使用调试器,但它仍然无法帮助我。