Trouble with Binary Search

亡梦爱人 提交于 2019-12-11 21:34:21

问题


there. I am trying to have a binary search of a text file. I am comparing text file one to text file two. However, My binary algorith seems to not work nd print out the element it has found. My text file 2 is a sorted list and my textfile1 is the key. I need some guidance on how to figure this problem out. Here is my code:

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

回答1:


The search key is changing on every iteration of the for loop in your binary_search implementation. Modify your implementation to take a single key, and wrap a for-loop around it for your vector of keys. However I agree with @H2CO3 that you should be using 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;   
    }
}

Output

1
1
0
0
0
1

If you wish to use your own binary_search, then you'll need to fix your current implementation.



来源:https://stackoverflow.com/questions/18814696/trouble-with-binary-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!