I was reading an algorithms book which had the following algorithm for binary search:
public class BinSearch {
sta
int mid=(l+h)/2;
can lead to integer overflow problem.(l+u) gets evaluated into a large negative integer value and its half is returned. Now,if we are searching for an element in an array, it would lead to "index out of range error."
However, the issue is resolved as:-
int mid=l+(h-l)/2;
int mid=((unsigned int)l+(unsigned int)h) >> 1 ;
where >> is the right shift operator.
Hope this helps :)
The problem is that (l+u)
is evaluated first, and could overflow int, so (l+u)/2
would return the wrong value.