【发布时间】:2012-10-05 02:22:19
【问题描述】:
我正在尝试在 Java 中实现二进制搜索,不起作用...不知道为什么,它总是给我一个错误,说找不到数字...
我不知道为什么,我没有看到任何错误:S 感谢您的帮助...
public void busquedaBinaria(int[] arreglo, int buscar) {
int centro = 0; //middle
int inferior = 0;
int superior = arreglo.length - 1;
boolean encontrado = false; //found flag
while(inferior <= superior)
{
centro = (superior + inferior) / 2;
if (arreglo[centro] == buscar){
System.out.println("-Number " + buscar + " found in the " + centro + " position.");
encontrado=true;
break;
}
else if (arreglo[centro] > buscar) {
superior = centro - 1;
}
else{
inferior = centro + 1;
}
System.out.println(centro);
}
if (encontrado == false) {
System.out.println("-Number " + buscar + " hasn't been found.");
}
}
【问题讨论】:
-
你能提供你传递给方法的值吗?
-
代码显示正确。确保
arreglo按升序排序。如果不是,那将解释您看到的行为。