字符串向量二分查找
我正在尝试使用二分搜索在字符串向量中查找用户输入的单词。但它总是返回一个正整数。 对向量进行排序并从 txt 文件中读取。 该文件看起来像。
aah
aal
aas
等等。
int binarySearchString(vector<string> arr, string x, int n) {
int lower = 0;
int upper = n - 1;
while (lower <= upper) {
int mid = lower + (upper - lower) / 2;
int res;
if (x == (arr[mid]))
res = 0;
if (res == 0)
return mid;
if (x > (arr[mid]))
lower = mid + 1;
else
upper = mid - 1;
}
return -1;
}
I am trying to find a user input word inside a string vector using binary search. But it always returns a positive integer.
The vector is sorted and read from a txt file.
The file looks like.
aah
aal
aas
and so on.
int binarySearchString(vector<string> arr, string x, int n) {
int lower = 0;
int upper = n - 1;
while (lower <= upper) {
int mid = lower + (upper - lower) / 2;
int res;
if (x == (arr[mid]))
res = 0;
if (res == 0)
return mid;
if (x > (arr[mid]))
lower = mid + 1;
else
upper = mid - 1;
}
return -1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,除非 x == (arr[mid]) 为 true,否则这段代码应该抛出运行时异常,因为
res
将在下一个 if 语句中使用。已初始化。当我将res
初始化为某个负值时,该函数似乎可以工作。使用
binarySearchString(words, "bbb", 3); 调用它会返回
-1
。As it is, unless
x == (arr[mid])
is true, this code should throw a runtime exception becauseres
will be used in the next if statement before it's been initialized. When I initializeres
to some negative value, the function seems to work.Calling it with
binarySearchString(words, "bbb", 3);
returns-1
.