Hello Folks!
I am confused in updating mid value in binary search problems like sometimes (left+right)/2 results in infinite loop & sometimes (left+right+1)/2 results in infinite loop when updated with same left & right.
Any blog post on the same confusion?








This has to do with how you update the left and right values later.
If you do:
Then you need to use
mid=(left+right+1)/2.And if you do:
Then you need to use
mid=(left+right)/2.I guess there are different kinds of people, and I will never understand why everyone can't just base their binary searches on maintaining proper invariants.
The
R - L > 1condition guarantees that(L + R) / 2is strictly betweenLandR(easily proven by contradiction), so the while loop always terminates.Look at Errichto's blog/video here.