Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二进制搜索问题_Java_Binary Search - Fatal编程技术网

Java 二进制搜索问题

Java 二进制搜索问题,java,binary-search,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(

所以我试图通过电影导演的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;
      }
public int-binarySearch(字符串键){
int low=0,high=collection.length-1,mid=(低+高)/2;
while(低0){
低=中+1;
} 
否则{
高=中-1;
}
中等=(低+高)/2;
}
如果(低>高){
System.out.print(“导演不在您的dvd收藏中”);
返回-1;
}
其他的
System.out.print(“导演的电影”+collection[mid].getDirector()+“在索引中”);
中途返回;
}
首先, 确保数组按控制器排序,例如:

Comparator<DVD> comparator = Comparator.comparing(DVD::getDirector);
Arrays.sort(collection, comparator);

谢谢你简化了我笨拙的lambda

愚蠢的问题:这些
DVD
对象是按电影导演分类的吗?DVD对象是如何分类的?哇哈哈,我觉得很傻。谢谢,我之前已经按标题排序过了
int index = Arrays.binarySearch(collection, new DVD() {
  @Override
  String getDirector() {
    return key;
  }
}, comparator);