C++ implements binary search (topic 704)

Topic requirements: Given an integer array nums with n elements (in ascending order) and a target value target, write a function to search for the target in nums, and return the subscript if the target value exists, otherwise return -1

example

Input: nums= [-1,0,3,5,9,12]
 target = 9
 Output: 4
 Explanation: 9 appears in nums with subscript 4
Input: nums= [-1,0,3,5,9,12], target= 2
 Output: -1
 Explanation: 2 does not exist in nums so return -1

The first idea to get this topic is to traverse one by one, compare each element in the array with the target, and return the corresponding value as required according to the comparison result. If the element with the subscript i in the array is equal to the target, i will be returned; if the target is not found after traversing the entire array, it will return -1;

class Solution {
public:
    int search(vector<int>& nums, int target) {
        for(int i=0;i<nums.size();++i)
        {
            if(nums[i]==target)
            {
                return i;
            }
        }
        return -1 ;
    }
};

I believe that the first thought of most people who have not studied algorithms when they get this question is the same as me, using the method of traversal matching.

Of course, this can be done, and the result must be correct, but if there are too many elements in the array, there are 1 million elements, and it happens that the target we are looking for is the 999999th, so the method of traversal matching is can be very time consuming.

In fact, we can change our thinking to make the code execution easier, so we have to think of another way to solve it, which is the dichotomy method . 

Find the target value target in the ascending array nums[i], to be sure, for a certain value i and target:

  • if(nums[i]==target), then i is what we need
  • if(num[i]<target), the target can only be on the right side of i
  • if(num[i]>target), the target can only be on the left side of i

Based on the above basic facts, we can use the binary search method to find the target in the ordered array. The specific method is to define the search range as [left, right], and the initial search range is the entire array. Each time the midpoint mid of the search range is taken, the size of nums[mid] and target is compared. If they are equal, mid is the required subscript. If not, the search range is reduced by half according to the size relationship between nums[mid] and target . The condition for binary search is that the search range is not empty, that is, left<=right. If the target is in the array, the binary search can find the target and return the subscript of the target in the array. If target is not in the array, -1 is returned.

The specific code is as follows

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left=0,right=nums.size()-1;
        while(left<=right)
        {
            int mid=(right-left)/2+left;
            if(nums[mid]==target)
            {
                return mid;
            }
            else if(nums[mid]>target)
            {
                right=mid-1;
            }
            else
            {
                left=mid+1;
            }
        }
        return -1;
    }
};

Let's put it in vs and test it

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

int search(vector<int>& nums, int target) {
    int left = 0, right = nums.size() - 1;
        while (left <= right)
        {
            int mid = (right - left) / 2 + left;
            if (nums[mid] == target)
            {
                return mid;
            }
            else if (nums[mid] > target)
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }
        return -1;
 }

int main()
{
    vector<int> vec{ 1,4,5,7,11,14,18 };
    cout << "vec: ";
    for (auto c : vec)
    {
        cout << c << " ";
    }
    cout << endl;
    /*int tar = 5;*/
    int tar = 2;
    int i=search(vec, tar);
    if (i >= 0)
        cout << tar<<" index is " << i << endl;
    else
        cout << tar<<" not found" << endl;
}

Test the two numbers separately, the results are as follows: 

Guess you like

Origin blog.csdn.net/yangSHU21/article/details/130567061