I need help with implementing the binary search algorithm, can someone tell me what's wrong with my code:
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
解决方案
I think you made a mistake when update lowerBoundary and upperBoundary.
It may be:
if(myStore.get(mid).compareTo(idToSearch) < 0){
lowerBoundary = mid + 1;
} else {
upperBoundary = mid - 1;
}
And why don't you break the loop if you find the element at mid?