将二叉搜索与向量一起使用

Using Binary Search with Vectors.

本文关键字:一起 向量 搜索      更新时间:2023-10-16

我正在尝试实现一种算法,该算法对于第一个向量中的每个字符串,它会在第二个向量中进行二分搜索,如果找到匹配项,它将输出"YES:",否则将输出"No:"。

现在在我的程序中,我的算法总是输出"NO:",我无法找出出了什么问题。任何提示或提示将不胜感激。

我的二叉搜索:

bool binary_search(const vector<string>& sorted_vec, 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;
    if (key > sorted_vec[mid]){
        left = mid+1;
   } else if (key < sorted_vec[mid]){                                        
        right = mid;
   } else {                                                                  
        return true;
            }                                                                
        return false;                                                        
    }
}

我的算法:

if(algo_speed == "fast"){
    string key = fileContent[i];
    while(getline(ifs1, line)){
            fileContent1.push_back(line);
    }
    sort(fileContent1.begin(), fileContent1.end());
    for(size_t i = 0; i < fileContent.size(); i++){
    string temp = fileContent[i];
    bool found = binary_search(fileContent1,temp) ;
     if(found == true) {
            cout << "YES:" << fileContent.at(i) << endl;
        } else {
            cout << "NO:" << fileContent.at(i) << endl;
        }
    }

}

您在第一次未命中时退出函数,并带有错位的return false

bool binary_search(const vector<string>& sorted_vec, 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;
      if (key > sorted_vec[mid]){
          left = mid+1;
      }
      else if (key < sorted_vec[mid]){                                        
        right = mid;
      }
      else {                                                                  
        return true;
     }                                                                                                               
   }
   return false;      
}