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.
Welche ist richtig? –
Was sind die Wörter? Deine lineare Suche sagt, dass keiner von ihnen gefunden wurde. – Mritunjay
schlagen vor '' equals' anstelle von '==' für Strings zu verwenden, wird auch das Array sortiert? – nullpointer