我需要帮助实现二进制搜索算法,有人能告诉我我的代码有什么问题吗:
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
最佳答案
我认为您在更新lowerBoundary
和upperBoundary
时犯了错误。
可能是:
if(myStore.get(mid).compareTo(idToSearch) < 0){
lowerBoundary = mid + 1;
} else {
upperBoundary = mid - 1;
}
如果在
mid
找到元素,为什么不中断循环?关于java - 二进制搜索实现Java算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22752363/