# Thread: binsearch algorithm, weird division into intervals

1. ## binsearch algorithm, weird division into intervals

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.

2. Probably a typographical error. It should have been:
Code:
`high = mid - 1;`

3. By the way, why do I need to pass size of an array (int n) to the function, isn't it already built-in into the argument of int v[] (since it has to be defined eg. as int v[20]) ?

4. Originally Posted by Pole
By the way, why do I need to pass size of an array (int n) to the function, isn't it already built-in into the argument of int v[] (since it has to be defined eg. as int v[20]) ?
No, because in binsearch, v is a pointer, not an array. Furthermore, what if you wanted to use this with an array named v1, of size 200?

5. Originally Posted by Pole
By the way, why do I need to pass size of an array (int n) to the function, isn't it already built-in into the argument of int v[] (since it has to be defined eg. as int v[20]) ?
When you pass an array you really pass a pointer to the first element of the array. Thus the compiler doesn't know the size of the array.
This is really an advantage because you can always pass an subarray to the function which makes the function more general/flexible.

Bye, Andreas