There's something that I don't get with the binary search code on C.
int binarySearch(int a[], int n, int x)
{
int low=0, mid, high=n-1;
while(low <= high)
{
mid = (low + high) / 2;
if (x < a[mid])
high = mid - 1;
else if (x > a[mid])
low = mid + 1;
else
return mid;
}
return -1;
}
Why does the while loop while(left<=right)
can't be written: while(left<right)
? Will this change effect things?
Take a simple case of
int a[1] = {5};
printf("%d\n", binarySearch(a, 1, 5));
With while(low < high)
, code prints -1 (did not find - wrong answer).
With while(low <= high)
, code prints 0 (found - right answer).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments