Suppose there is a function f(x), where x is double.
The function has the form of a step:

Suppose we can find the value of f(xi) for every xi, but we don’t know the value of x0.
How to find x0 in O(LogN)?
double l=0,r=inf
for(int iter=0;iter<100;iter++)
{
double mid=(l+r)/2;
if(f(mid)==0) l=mid;else r=mid;
}
The answer is mid
Ok,it’s easy.
Now let’s take a function with an integer domain.
int l=l0;int r=r0; //here we should take lo,r0
// such that f(lo)=0, and f(ro)=1
while(r-l>1)</em>
{
int mid=(l+r)/2;
if(f(mid)==0) l=mid;else r=mid;
}
What do we get? f(lo)=0(why? because we never assigned to l “something” if f(“something”)!=0) ! and f(ro)=1(the same thing,we always have f(newr)=1),and (ro-lo)==1! That’s what we need.
No let’s think what happens if lo and are negative,for example,-1 and -6
(-1+-6)/2= -7/2..here we should have -4 to make the binary search working,but we have -3.
That’s why it’s better to replace the expression for mid with
mid=l+(r-l)/2
Now we have mid=-6+(-1-6)/2=-6+(5/2)=-4.Nice:)