我在实现二分查找算法方面需要帮助,谁能告诉我我的代码有什么问题:
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/