2016-08-11 14 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