二进制搜索的麻烦 [英] Trouble with Binary Search

查看:205
本文介绍了二进制搜索的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那里。我试图有一个文本文件的二进制搜索。我比较文本文件一到文本文件二。然而,我的二进制算法似乎不工作nd打印出它发现的元素。我的文本文件2是一个排序的列表,我的textfile1是键。
我需要一些指导如何解决这个问题。这是我的代码:

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


推荐答案

搜索关键字在binary_search实现中的for循环的每次迭代时都会改变。修改您的实现以获取单个键,并围绕它的for循环为您的键的矢量。但我同意@ H2CO3,你应该使用 std :: binary_search

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

如果您想使用自己的binary_search,那么您需要修复当前的实现。

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

这篇关于二进制搜索的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆