[C++] Introduction and code of binary search

In the process of brushing the questions, the author found that some grammars and algorithms are easy to forget, so this series of notes for brushing questions wants to record some common grammars and algorithms for easy review and consolidation. The content of this series is updated synchronously according to the progress of brushing the questions.

Introduction

Binary search , also known as binary search , is an algorithm for finding an element in an ordered sequence. The algorithm is based on the premise of an ordered sequence, and each search can reduce the search range by half.

The basic idea

Take an ascending sequence of numbers (sorted from smallest to largest) as an example. First find the middle element Middle
of the array , and then compare it with the target element Target you are looking for . If the middle element Middle is equal to Target, the search ends ; if the middle element Middle is smaller than Target, the left element will only be smaller than Middle and will not be equal to Target, then we only need to find Target in the right element ; if the middle element Middle is greater than Target, then we only need to find Target in the left element .

the complexity

Time complexity: O(log n) , where n is the length of the array.
Space complexity: O(1) . We only need constant space for a few variables.

question

Given a sorted array and a target value , find the target value in the array and return its index . If the target value does not exist in the array, returns the position where it will be inserted in order .

the code

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

int binary_search(vector<int>& nums, int target)
{
    
    
	int n = nums.size();
	int left = 0, right = n - 1, flag = n;
	while (left <= right) {
    
    
		int mid = left + ((right - left) >> 1);
		if (target <= nums[mid]) {
    
    
			flag = mid;
			right = mid - 1;
		}
		else {
    
    
			left = mid + 1;
		}
	}
	return flag ; //返回索引或将被插入的位置
}
int main()
{
    
    
	vector<int> nums={
    
     1,3,5,6 };
	int target = 3;
	count << binary_search(nums, target) << endl;
	return 0;
}

Note: left + ((right -left) >> 1) == (left + right) /2
left + right may exceed the maximum value that the basic type can hold in some cases, and >> (binary right shift ) is faster than /, so it is better to use the expression on the left.

Guess you like

Origin blog.csdn.net/weixin_44842318/article/details/127388394