我正在为我的动态数组类编写一个多搜索算法,并且我的实现尝试了二进制搜索,但我的程序不会正确设置我的整数mid
的值。
以下是该方法的代码:
public static boolean search(int[] array, int value) {
int first = 0, last = array.length - 1, mid = ((first + last) / array.length);
System.out.println(first + " - " + mid + " - " + last);
while(true) {
System.out.println(first + " - " + mid + " - " + last);
if (value == array[mid]) {return true;}
if (first == last || mid == last || mid == first) {return false;}
if (value > array[mid]) {
first = mid;
mid = (first + last) / (last + 1);
}
if (value < array[mid]) {
last = mid;
mid = (first + last) / (last + 1);
}
System.out.println(first + " - " + mid + " - " + last);
}
}
我使用数百个测试运行程序,但mid的值始终为0(输出为0 - 0 - 111725
或0 - 0 - 127
或0 - 0 - 15
)。
非常感谢所有帮助!
答案 0 :(得分:2)
不应该&#39; T:
mid = ((first + last) / array.length)
......实际上是这样的
mid = ((first + last) / 2)
...而是让你获得mid
?
要获得2个值之间的中间值,您需要添加值 并除以2 。
答案 1 :(得分:1)
确保您的数组 升序 顺序:
public static boolean search(int[] array, int value) {
int first = 0, last = array.length - 1, mid = ((first + last) / 2); //Divide by 2
System.out.println(first + " - " + mid + " - " + last);
while(true) {
System.out.println(first + " - " + mid + " - " + last);
if (value == array[mid]) {return true;}
if (first == last || mid == last || mid == first) {return false;}
if (value > array[mid]) {
first = mid;
mid = (last + first) / 2; //Divide by 2
}
if (value < array[mid]) {
last = mid;
mid = (first + last) / 2; //Divide by 2
}
System.out.println(first + " - " + mid + " - " + last);
}
}