简体   繁体   English

使用向量进行二分搜索

[英]Binary Search using a vector

So.. Ive already learnt of Binary Search and how it works and even tried it using a constant array without any input from the user , But now im trying to apply vector instead of array to have the user enter the values of both the list in which to search the numbers from vector and the target to search for.所以..我已经了解了二分搜索及其工作原理,甚至在没有用户任何输入的情况下使用常量数组进行了尝试,但现在我尝试应用向量而不是数组来让用户输入两个列表的值从向量中搜索数字和要搜索的目标。 Here i used a normal divide&conquer while using an array在这里,我在使用数组时使用了普通的分治法

using namespace std;
int Binary_search(int x[],int size,int target){
    int maximum= size-1;
    int minimum = 0;
    int mean;
    while (maximum>minimum){
        mean = (maximum+minimum)/2;
        if (x[mean] == target){
            cout << "The number you're looking for is found! \n";
            return mean;
        }
        else if(x[mean] > target){
            maximum = (mean-1);
        }
        else{
            minimum = (mean+1);
        }
    }
    return -1;
}
int main(){
    int x[]={1,2,3,4,5};
    int a=sizeof(x)/sizeof(x[0]);
    int target=4;
    int show=Binary_search(x,a,target);
    if (show != -1){
        cout << "Your result is in the index: " << show;
    }
    return 0;
}

My problem is that I made pretty much the same method using vector instead but it's showing either an infinite amount of **Your result is found at the index: ** (number of wrong index) .我的问题是我使用 vector 做了几乎相同的方法,但它显示了无限量的 **Your result is found at the index: ** (number of wrong index) 。 Or it doesnt show any result at all or even show that the result is not found , Differs each time somehow.或者它根本不显示任何结果,甚至显示未找到结果,每次都以某种方式不同。 Here's while using the vector这是使用向量时

#include <iostream>
#include <vector>
using namespace std;
int Binary_search(vector<int>x,int target){
    int maximum=(x.size())-1;
    int minimum = 0;
    int mean;
    while (maximum>minimum){
        mean = (maximum+minimum)/2;
        if (x[mean] == target){
            cout << "The number you're looking for is found! \n";
        }
        else if(x[mean] > target){
            maximum = (mean-1);
        }
        else{
            minimum = (mean+1);
        }
    }
    return -1;
}
int main(){
    unsigned int i;
    int n;
    vector<int>x;
    cout << "Enter the amount of numbers you want to evaluate: ";
    cin >> i;
    cout << "Enter your numbers to be evaluated: " << endl;
    while (x.size() < i && cin >> n){
        x.push_back(n);
    }
    int target;
    cout << "Enter the target you want to search for in the selected array \n";
    cin >> target;
    int show = Binary_search(x,target);
    if (show == -1){
        cout << "Your result is not found ! ";
    }
    else{
        cout << "Your result is in the index: " << show;
    }
    return 0;
}

So I think the problem is in this part int maximum=(x.size())-1;所以我认为问题出在这部分int maximum=(x.size())-1; , Maybe it's about how to use the size of vectors ? ,也许是关于如何使用向量的大小? Could someone enlighten me up to this有人可以启发我吗

Well, the other answers have helped to solve the issue, but in case you didn't know, there are built-in functions for performing binary search in C++ that you can use them.好吧,其他答案已经帮助解决了这个问题,但如果你不知道,你可以使用它们在C++中执行二进制搜索的内置函数。

I will list the functions related binary search:我将列出与二分查找相关的函数

  • sort : you can use binary search only on a sorted data, so you must guarantee that the data is sorted, before searching. sort :您只能对已排序的数据使用二分搜索,因此您必须在搜索之前保证数据已排序。
  • lower_bound : this function returns an iterator to the first element that is greater than or equal to value. lower_bound :此函数返回一个迭代器,指向大于或等于value 的第一个元素。
  • upper_bound : this function returns an iterator to the first element that is greater than value. upper_bound :此函数返回一个迭代器,指向大于value 的第一个元素。
  • binary_search :: this functions returns a boolean , whether the value is found or not (exactly as your program). binary_search :: 此函数返回一个boolean ,无论是否找到该值(与您的程序完全一样)。

Here's a code sample that demonstrates the previous functions:下面的代码示例演示了之前的功能:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iostream>

typedef std::vector<int>::iterator iter;

int main() {

    std::vector<int> vec = {10, 20, 30, 30, 20, 10, 10, 20};

    // sort the data
    // the data will be:
    // 10, 10, 10, 20, 20, 20, 30, 30
    std::sort(vec.begin(), vec.end());

    // index of the first element, greater than or equal to 20
    iter low = std::lower_bound(vec.begin(), vec.end(), 20);

    // index of the first element, greater than 20
    iter high = std::upper_bound(vec.begin(), vec.end(), 20);

    std::cout << "index of first element, greater than or equal to 20 is: " << (low - vec.begin()) << '\n';

    std::cout << "index of first element, greater than to 20 is: " << (high - vec.begin()) << '\n';

    // classic binary search
    // check whether a givin value exists in the array or not
    if (std::binary_search(vec.begin(), vec.end(), 99)) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }

}

You need to return mean after this line您需要在此行之后return mean

cout << "The number you're looking for is found! \n";

Just like you do in the array version.就像你在数组版本中所做的一样。

Also, as mentioned in the comments, this will only work if the user enters in sorted data.此外,如评论中所述,这仅在用户输入排序数据时才有效。

problems:问题:

  1. no return.没有回报。 add添加
cout << "The number you're looking for is found! \n";
return mean;
  1. goes too fast, it might skip some numbers走得太快,可能会跳过一些数字
else if(x[mean] > target)
{
    maximum = mean;
}
else
{
    minimum = mean;
}

why goes too fast might be a problem?为什么走得太快可能是个问题? try when试试什么时候

vector<int>x{1,2,3,4,5,6};
int target = 4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM