【问题标题】:Using Binary Search with Vectors.对向量使用二分搜索。
【发布时间】:2013-09-17 11:09:44
【问题描述】:

我正在尝试实现一个算法,它对第一个向量中的每个字符串在第二个向量中进行二进制搜索,如果找到匹配项将输出“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;
        }
    }

}

【问题讨论】:

    标签: c++ algorithm search vector binary


    【解决方案1】:

    您将在第一次错过时退出您的函数,并使用错位的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;      
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多