I am implementing a simple binary search.But my program is not giving the correct solution on some values. long long low=1,high=100000000000000,mid=0,ans=0;
while ( high > low)
{
mid =low +(high-low)/2;
ans=mid;
if( ans==m )
return ans;
if (ans > m)
high=mid-1;
else
low=mid+1;
} return low;
This binary search should return the value equal to m,But this is failing on most of the cases. Can anyone tell me the mistake??
mid = (low + high) / 2 — correct.
if (ans > m) high = mid — correct.
(low + high) / 2 = low + (high — low) / 2
You should change the following parts and it should be fine
However, I guess that most of the time you want
ans = f(mid)
Your mistake is that you ask such a question here.
I'd advise you to run your code step-by-step with the help of a debugger. This should be much more useful than if somebody will point to your error.
UPD. But I'm late, you got your hint. You've lost a small, but valuable lesson :).
+1, but running binary search step-by-step didn't helped me a lot, but online lecture did. There was a rule you must grant for l,r. Here is total idea.
try it on ideone
thanks Got it!!!
I will keep this in mind next time.