Integer binary search template

Many binary integer than half of real trouble, because of the border issue, handled properly prone to an endless loop.
There are two versions of the half way

Version 1: the interval [l, r] is divided into the interval [l, mid] and [mid + 1, r], r = mid operable to update or l = mid + 1,
At this mid = l + r >> 1.

code show as below:

while(l<r)
{
     mid=l+r>>1;
     if(check(mid))
         r=mid;
     else
         l=mid+1;
}
Version 2: the interval [l, r] is divided into the interval [l, mid-1] and [mid, r], the update operation is r = mid-1 or l = mid,
At this time, mid = (l + r + 1) >> 1. (Not plus 1, then an infinite loop occurs)

code show as below:

while(l<r)
{
     mid=l+r>>1;
     if(check(mid))
         l=mid;
     else
         r=mid-1;
}


Share Yan template from God acwing founder https://www.acwing.com/blog/content/31/

Guess you like

Origin blog.csdn.net/weixin_43693379/article/details/91191669