所以我试图对电影导演的DVD对象数组进行二进制搜索,但我遇到了一点小麻烦。当我运行我的二进制搜索时,它只表明导演不在电影集合中,当它在时。我仍然不是最擅长搜索的人,所以任何给我指明正确方向的建议都将不胜感激。
public int binarySearch(String key) {
int low=0,high=collection.length-1,mid=(low+high)/2;
while (low <= high && collection[mid].getDirector().compareTo(key)!=0) {
if (key.compareTo(collection[mid].getDirector())>0){
low = mid + 1;
}
else {
high = mid - 1;
}
mid=(low+high)/2;
}
if (low>high){
System.out.print("the director is not in your dvd collection");
return -1;
}
else
System.out.print("the movie by director " + collection[mid].getDirector() + " is in index ");
return mid;
}发布于 2016-08-12 05:51:57
首先,确保您的数组是按控制器排序的,例如:
Comparator<DVD> comparator = Comparator.comparing(DVD::getDirector);
Arrays.sort(collection, comparator);然后,使用JDK的二进制搜索:
int index = Arrays.binarySearch(collection, new DVD() {
@Override
String getDirector() {
return key;
}
}, comparator);感谢简化了我笨拙的lambda!
https://stackoverflow.com/questions/38906438
复制相似问题