那里。我正在尝试对文本文件进行二进制搜索。我正在比较文本文件一和文本文件二。但是,我的二进制算法似乎无法工作并打印出它找到的元素。我的文本文件 2 是一个排序列表,我的文本文件 1 是关键。 我需要一些关于如何解决这个问题的指导。这是我的代码:
bool binary_search(const vector<string>& sorted_vec, const vector<string>& key) {
size_t mid, left = 0;
size_t right = sorted_vec.size(); // one position passed the right end
while (left < right) {
mid = left + (right - left)/2;
for(int i=0;i<sorted_vec.size();i++){
if (key[i] > sorted_vec[mid]){ //
left = mid+1;
}else if (key[i] < sorted_vec[mid]){
right = mid;
}else{
return true;
}
}
return false;
}
}
最佳答案
搜索键在 binary_search 实现中 for 循环的每次迭代中都会发生变化。修改您的实现以采用单个键,并为您的键 vector 围绕它包装一个 for 循环。但是我同意@H2CO3,你应该使用std::binary_search
:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> sorted_vec = {1, 2, 3, 4, 5, 6, 7, 8};
vector<int> keys = {3, 5, 19, 27, 0, 2};
int main() {
for(const auto &key : keys) {
cout << binary_search(sorted_vec.cbegin(), sorted_vec.cend(), key) << endl;
}
}
输出
1
1
0
0
0
1
如果您希望使用自己的 binary_search,则需要修复当前的实现。
关于c++ - 二进制搜索的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18814696/