嘗試在已排序的Book對象數組上執行二分搜索。Java二進制搜索
它工作不正常,它返回一些對象的正確結果,但不是全部。
我經歷了紙上的循環,似乎由於向上舍入數字可能會錯過一個數字。
任何想法如何使這項工作?
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;
這是功課嗎? – PSpeed 2010-02-27 11:24:44
我將它添加到一門課程中。只需要一個標準的搜索,但我想包括一個二進制搜索,以使其從人羣中脫穎而出 – user195257 2010-02-27 11:29:10