並べ替えられた Book オブジェクトの配列に対してバイナリ検索を実行しようとしています。
一部のオブジェクトでは正しい結果が返されますが、すべてではありません。
私は紙の上でループを調べましたが、#.5 を上に丸めるために数字が見逃される可能性があるようです。
これを機能させる方法はありますか?
Book found = null;
/*
* Search at the center of the collection. If the reference is less than that,
* search in the upper half of the collection, else, search in the lower half.
* Loop until found else return null.
*/
int top = numberOfBooks()-1;
int bottom = 0;
int middle;
while (bottom <= top && found == null){
middle = (bottom + top)/2;
if (givenRef.compareTo(bookCollection.get(middle).getReference()) == 0) {
found = bookCollection.get(middle);
} else if (givenRef.compareTo(bookCollection.get(middle).getReference()) < 0){
bottom = middle + 1;
} else if (givenRef.compareTo(bookCollection.get(middle).getReference()) > 0){
top = middle - 1;
}
}
return found;