Hello, I have another question regarding K&R. In the following code I've marked the suspicious element:
Code:
int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n -1;
while (low <= high) {
mid = (low+high)/2;
if (x < v[mid])
high = mid +1; /* here, I think +1 should be omitted */
else if (x > v[mid])
low = mid +1;
else
return mid;
}
return -1;
}
Taking for example 15 as the size of an array v, high = 14. Then mid is 7, if x is smaller than v[7] then program creates new bound high which would be equal to 8. In that way the interval is now 0 to 8 (9 spaces in array). That is quite stupid for me since we already know that the eigth element doesn't satisfy the condition.
If x is bigger than v[7] then low would be made equal to 8, new interval would be 8-14 (7 spaces in array).
Correct me please if I'm wrong.
Thanks in advance!