Binary search and binary boundary processing

What is binary search

Generally speaking, binary search is to find the range of answers in a sorted array, and take the middle value of the range each time. If this value is large, take the first half and continue to narrow the range; if this value is small, take the second half to narrow the range.
After each time, you can reduce the range of 1/2, and gradually get the answer.

Sample error boundary

Example question : https://www.acwing.com/problem/content/description/1229/
This question obviously can be divided into two points. If the enumeration is 1 to 100000,
set l=1,r=1e5,mid=(l+r )/2; In the
past, I always used l=mid+1 if mid was small; r=mid-1 if mid was large, but when the answer to this question is 5, the answer will be wrong. Why?
As shown in the figure, the first one in each line is l, the second is r, and the third is mid.
Insert picture description here
If the answer to this question is 5, when mid=4, l=mid+1, that is, l=5, then exit the loop , The final answer is 4.

boundary

(1) mid=(l+r)/2In fact, it is (l+r)/2 rounded down. When l=mid, r=mid+1, if l+1 exits the loop directly, the value of r=mid+1 has not been taken.
Because it is rounded down, that is l <= mid < r, mid is always less than the value of r, and it can be changed to r=mid when mid is large, that is

    while(l<r){
    
    
        int mid = (l+r)/2;
       判断成立语句;

        if(满足条件){
    
    
            ans=mid;
            l=mid+1;
        }
        else{
    
    
            r=mid;
        }
    }

(2) It can also be rounded up, ie mid=(l+r+1)/2. In the same way, l < mid <= rmid will never be equal to l. At this time, it can be changed to mid. If it is smaller, l=mid, and the code is available

    while(l<r){
    
    
        int mid = (l+r+1)/2;
       判断成立语句;

        if(满足条件){
    
    
            ans=mid;
            l=mid;
        }
        else{
    
    
            r=mid-1;
        }
    }

Guess you like

Origin blog.csdn.net/qq_45758578/article/details/113209836