我需要帮助实现二进制搜索算法,有人可以告诉我我的代码有什么问题:
public int bsearch(Item idToSearch) {
int lowerBoundary = 0;
int upperBoundary = myStore.size() - 1;
int mid = -1;
while(upperBoundary >= lowerBoundary) {
mid = (lowerBoundary + upperBoundary) / 2;
//if element at middle is less than item to be searched, than set new lower boundary to mid
if(myStore.get(mid).compareTo(idToSearch) < 0) {
lowerBoundary = mid - 1;
} else {
upperBoundary = mid + 1;
}
} //end while loop
if(myStore.get(mid).equals(idToSearch)) {
return mid;
} else {
return -1; // item not found
}
} // end method
答案 0 :(得分:4)
我认为您在更新lowerBoundary
和upperBoundary
时犯了一个错误。
可能是:
if(myStore.get(mid).compareTo(idToSearch) < 0){
lowerBoundary = mid + 1;
} else {
upperBoundary = mid - 1;
}
如果你在mid
找到元素,为什么不打破循环?
答案 1 :(得分:0)
我会
mid = (hi + lo) >>> 1;
来避免导致错误的溢出。答案 2 :(得分:0)
第一个问题是边界问题,你也应该停下来以防他找到价值,但他并没有导致可能被忽视。
while(upperBoundary >= lowerBoundary)
{
mid = (lowerBoundary + upperBoundary) / 2;
if (myStore.get(mid).equals(idToSearch)) break; // goal
if(myStore.get(mid).compareTo(idToSearch) < 0)
{
lowerBoundary = mid + 1;
}
else
{
upperBoundary = mid - 1;
}
}