【发布时间】:2015-12-17 16:52:17
【问题描述】:
我正在尝试实现一种基本形式的二分搜索。我创建了一个数组并用线性值填充。现在只是试图对其进行排序以找到一个数字及其索引。问题是它陷入了一个恒定循环并返回零。它通过嵌套循环,因为它打印但无法找到目标值。下面是代码
for (int i= 1; i < 10000 ; i++){
studentID[i] = i;
}
Students studentIDNumber = new Students();
studentIDNumber.binarySearch(studentID, 400);
public void binarySearch(int[] studentID, int targetID){
System.out.println("helloworld");
int position = -1;
int suspect;
int suspectIndex = 0;
int lastSuspectIndex = studentID.length-1;
while(position == -1)
{
assert(suspectIndex<lastSuspectIndex);
suspectIndex = ((studentID.length-1)/2);
lastSuspectIndex =suspectIndex;
suspect=studentID[suspectIndex];
System.out.println(suspect);
if(suspect == targetID){
position = suspectIndex;
System.out.println(suspectIndex +" is where the ID #"+targetID+" is sotred");
break;
}
if(suspect < targetID){
suspectIndex= suspectIndex+(suspectIndex/2);
position = -1;
}
if(suspect > targetID){
suspectIndex= suspectIndex-(suspectIndex/2);
position = -1;}
else {
System.out.println("ID not found " );
}
}
}
【问题讨论】:
-
您的问题始于语句 lastSuspectIndex =suspectIndex; 1,2,3,4,5,6,7 现在空运行代码,你会得到,如果 TargetID>SuspectID 它一定是suspectId=SuspectId+(SuspectID/2);
-
您正在将
suspectIndex重置为每个循环长度的一半。它每次都检查相同的位置,这就是它永远不会退出的原因。您应该将第一次初始化放在循环之外。不幸的是,代码中还有很多其他问题(例如,如果suspectIndex是 7500 并且太小,那么它将变为 7500 + 7500 / 2,然后超出范围)。
标签: java sorting search binary