public static int binSearch (double[] list, double item)
{
int bottom = 0; // lower bound of subarray
int top = list.length - 1; // upper bound of subarray
int middle; // middle of subarray
boolean found = false; // to stop if item found
int location = -1; // index of item in array
while (bottom <= top && !found)
{
middle = (bottom + top)/2;
if (list[middle] == item) // success
{
found = true;
location = middle;
}
else if (list[middle] < item) // not in bottom half
bottom = middle + 1;
else // item cannot be in top half
top = middle - 1;
}
return location;
}
在我的教科书里,我有这个代码。我想知道为什么我需要 bottom <= top
不仅仅是 !found
. 不应该 low
总是变小?所以唯一的决定因素就是!找到了。
谢谢
暂无答案!
目前还没有任何答案,快来回答吧!