【发布时间】:2014-05-10 05:57:39
【问题描述】:
我在实现二进制搜索算法方面需要帮助,谁能告诉我我的代码有什么问题:
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
【问题讨论】:
-
调试器肯定能告诉你哪里出了问题。
-
一个完全不正确的算法...
标签: java algorithm search binary