2016-11-16 7 views
-1

Ich frage mich, warum meine binäre Suche einen anderen Wert als meine lineare Suche zurückgibt. Kann mir jemand erklären, was ich falsch mache? Sollte ich etwas anderes zurückgeben?Binäre Suche nach einem Array von Strings

public class BinarySearch extends SearchAlgorithm 
{ 
    public int search (String [] words, String wordToFind) throws ItemNotFoundException { 
    int lowIndex = 0; 
    int highIndex = words.length - 1; 
    while (lowIndex <= highIndex) { 
     int midIndex = (lowIndex + highIndex)/2; 
     if ((words[midIndex]).equals(wordToFind)) { 
      return midIndex; 
     } 
     if (wordToFind.compareTo(words[midIndex]) > 0) { //wordToFind > midIndex 
      lowIndex = midIndex + 1; 
     } 
     if (wordToFind.compareTo(words[midIndex]) < 0) { //wordToFind < midIndex 
      highIndex = midIndex - 1; 
     } 
     lowIndex++; 
    } 
    return -1; 
} 

}

Hier ist, was es gibt. Die erste Gruppe ist mit der linearen Suche und die zweite mit der binären.

DISCIPLINES found at index: 11780 taking 0 comparisons. 
TRANSURANIUM found at index: 43920 taking 0 comparisons. 
HEURISTICALLY found at index: 18385 taking 0 comparisons. 
FOO found at index: -1 taking 0 comparisons. 

DISCIPLINES found at index: 11780 taking 0 comparisons. 
TRANSURANIUM found at index: 43920 taking 0 comparisons. 
HEURISTICALLY found at index: -1 taking 0 comparisons. 
FOO found at index: -1 taking 0 comparisons. 
+0

Welche ist richtig? –

+0

Was sind die Wörter? Deine lineare Suche sagt, dass keiner von ihnen gefunden wurde. – Mritunjay

+2

schlagen vor '' equals' anstelle von '==' für Strings zu verwenden, wird auch das Array sortiert? – nullpointer

Antwort

-1

Versuchen Sie, Ihre Logik zu ändern:

int midIndex = (lowIndex + highIndex)/2; 
while (lowIndex <= highIndex) {  
    if ((words[midIndex]).equals(wordToFind)) { //use equals 
     return midIndex; 
    } 
    if (wordToFind.compareTo(words[midIndex]) > 0) { //wordToFind > midIndex 
     lowIndex = midIndex + 1; 
    } 
    if (wordToFind.compareTo(words[midIndex]) < 0) { //wordToFind < midIndex 
     highIndex = midIndex - 1; 
    } 
// getting rid of infinite loop when the value is not in the list 
    if (lowIndex==highIndex && !wordToFind.compareTo(words[midIndex]) { 
     return -1; 
    } 
    midIndex = (lowIndex + highIndex)/2; // notice removing lowindex++ 
} 

Die lowIndex++ innerhalb des while war nicht erforderlich, da diese die lowIndex unabhängig von der BS zu aktualisieren war algorithn die Indizes auf dem Vergleich mit midIndex Wert basierend aktualisieren.

+0

Die Verwendung von '<=' in der while-Bedingung führt zu einer Endlosschleife, wenn das Suchwort nicht im Array ist. –

+0

Danke, das hat funktioniert! Kannst du kurz erklären warum/wie? – iloveprogramming

+0

@JimGarrison aktualisiert mit einer Rückkehr für die Endlosschleife Bedingung – nullpointer