// Returns location of key, or -1 if not found
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( l <= r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
Optimized Binary Search Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
elsereturn -1;
}
The author claims, we are reducing comparison by 1 in the while loop. I can see that in the while loop but I don't think it looks correct. Didn't we just move the comparison to outside the while loop in another if, else loop? Is this really an optimized solution?