二进制搜索麻烦

时间:2016-08-11 21:28:54

标签: java binary-search

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

1 个答案:

答案 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!