int arr[] = {21, 44, 56, 76, 89, 91, 102, 120, 143, 167, 242, 291}; //array.length == 11.
int goal = 143;
int i = (arr.length - 1)/2;
int upper = arr.length -1;
int lower = 0;
int found = 0;
boolean foundYes = false;
int j;
while (foundYes = false) {
if(arr[i] > goal) {
upper = i;
i = (upper - lower)/2;
} else if(arr[i] < goal) {
lower = i;
i = (upper - lower)/2;
} else if(arr[i] == goal) {
found = i;
foundYes = true;
break;
}
}
System.out.println(found);
我正在尝试在数组中找到值为143的索引。所以arr [x] = 143,其中找到x是目标
我尝试了带有断点的调试器,但它并没有给我很多信息或细节。
我从调试器获得的内容:因此它检测到arr[i] == arr[5] == 91 < 143
但它从未更改任何内容,并且找到的内容返回为found==0
这里有什么问题?
编辑:我已经开始工作了:
int arr[] = {21, 44, 56, 76, 89, 91, 102, 120, 143, 167, 242, 291}; //array.length == 11.
int goal = 143;
int i = (arr.length - 1)/2; //first arr[i] = 91.
int upper = arr.length -1;
int lower = 0;
int found = 0;
boolean foundYes = false;
int j;
while (foundYes == false) {
if(arr[i] > goal){
upper = i;
i = upper + (upper - lower)/2;
}
else if(arr[i] < goal){
lower = i;
i = lower + (upper - lower)/2;
}
else if(arr[i] == goal){
found = i;
foundYes = true;
break;
}
}
System.out.println(found);
}
}
答案 0 :(得分:2)
有两个问题。首先,while
中的语法不正确,这就是您的程序没有被发送到无限循环的原因。您想要foundYes == false
,而不是foundYes = false
。第二个问题(您可能尚未遇到)是您如何设置i
。假设upper
等于8
且lower
等于7
。 i
变成了什么?看看那个,看看你是否可以从中找到它。