3

I'm trying to implement an algorithm that for each string in the first vector it does a binary search in the second vector and will output "YES:" if it finds a match or "No:" otherwise.

Right now with my program my algo always outputs "NO:" and I can't find out what's going wrong. Any hints or tips would be appreciated.

My Binary search:

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;                                                        
    }
}

My Algo:

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;
        }
    }

}

1 Answer 1

7

You are exiting your function on the first miss with the misplaced 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;      
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.