Find elements by binary method

Fundamental

The idea of ​​binary search is very simple. We set the element numbers at the beginning and end of the element to be first and last respectively.
In addition, you need to set another element mid.
The realization idea of ​​the mid = (first+last)/2
dichotomy is that each search uses the middle value of the current sequence as a comparison point, so that each time the search range is reduced to half of the elements in the current sequence. Here is the code implementation:


//二分法查找
class Solutions2
{
public:
    searchBin(const vector<int>& nums,int target)
    {
        int first = 0;
        int last = nums.size();
        int mid = 0;
        while(first != last)
        {
            mid = (last+first)/2;
            if(nums[mid] == target)
                return mid;
            else
            {
                if(target > nums[mid])
                    first = mid + 1;
                if(target < nums[mid])
                    last = mid - 1;
            }
        }
        return -1;
    }
};

Here is the test code:

#include<iostream>
#include<vector>
using namespace std;

//二分法查找
class Solutions2
{
public:
    searchBin(const vector<int>& nums,int target)
    {
        int first = 0;
        int last = nums.size();
        int mid = 0;
        while(first != last)
        {
            mid = (last+first)/2;
            if(nums[mid] == target)
                return mid;
            else
            {
                if(target > nums[mid])
                    first = mid + 1;
                if(target < nums[mid])
                    last = mid - 1;
            }
        }
        return -1;
    }
};



//主函数
int main(void)
{

    vector<int> a;
    a.push_back(1);
    a.push_back(1);
    a.push_back(1);
    a.push_back(2);
    a.push_back(2);
    a.push_back(3);
    a.push_back(4);
    a.push_back(4);
    a.push_back(4);
    a.push_back(4);
    a.push_back(5);

    cout<<"after binary search "<<endl;
    Solutions2 ss;

    int return_binSort = ss.searchBin(a,3);
    cout <<"the result is :"<<return_binSort;
    cout<<endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325458856&siteId=291194637