2016-08-11 27 views
2

所以我试图通过电影导演的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; 
     } 
+4

愚蠢的问题:这些“DVD”对象是否由电影导演排序? –

+0

DVD对象是如何排序的? –

+0

哇哈哈我觉得很傻。谢谢,我以前按标题排序 –

回答

2

首先, 确保您的阵列是由导演来分类,例如:

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); 

谢谢@Boris简化我笨拙的lambda!