【发布时间】:2010-02-28 20:25:36
【问题描述】:
尝试对 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;
【问题讨论】:
-
我将其添加到课程作业中。只需要一个标准搜索,但我也想包括一个二分搜索,让它在人群中脱颖而出
标签: java binary-search