I\'m reading this post and trying to figure out how could we determine invariant relation for binary search. To be specific, in the two examples he gave, why these two invariant
You wrote
The part A[start] < target < A[end] is obvious
but it's obviously wrong because initial values should be start = 0, end = N-1 (not -1, N). BTW, you don't need any invariant for the case described in your link (array of distinct elements).
This will work without problems and easy to understand.
int arr[] = {0,1,2,3,4,5,6,7};
int N = sizeof (arr) / sizeof (arr[0]);
int target = 4;
int l = 0, r = N-1;
while( l <= r ) {
int mid = (l+r)>>1;
if( arr[mid] == target )
return mid;
if( arr[mid] < target )
l = mid + 1;
else
r = mid - 1;
}
return -1; // not found