我必须使用二分搜索来查找用户输入的电影,但是,当执行某些电影或不在列表中的电影时,搜索会永远循环。有人告诉我这是因为我不能使用“">”或“<" with strings and I have to use the compare() function but I am having trouble.
int main() { ...
pos = findMovieTitle(MovieArray, MOVIES_SIZE, Movies.title);
if(pos == -1) {
cout << Movies.title << " was not found" << endl << endl;
} else {
cout << "Title: " << MovieArray[pos].title << endl;
cout << "Year Released: " << MovieArray[pos].year << endl;
cout << "Revenue: " << MovieArray[pos].revenue << endl << endl;
}
...
}
int findMovieTitle(const Movies topMovies[], const int SIZE, string title) {
int first = 0;
int last = SIZE - 1;
int middle;
int pos = -1;
bool found = false;
while (!found && first <= last) {
middle = (first + last) / 2;
if(topMovies[middle].title == title) {
pos = middle;
found = true;
} else if (topMovies[middle].title.compare(title) > 0) {
last = middle - 1;
} else {
first = middle - 1;
}
}
return pos;
}
我搜索了一下,发现如果第一个字符串更大,它会返回一个正整数,所以我尝试了这个,但没有修复它。
这一行:
first = middle - 1;
需要:
first = middle + 1;