Start New Discussion within our Software Development Community

I found the following logic for binary search from the standard book i feel it fails in some

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */
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;
else if (x > v[mid])
low = mid + 1;
else /* found match */
return mid;
}
return -1; /* no match */
}



#include <stdio.h>
int binsearch(int *v, int n, int x);
int main(void)
{
    int v[10]={2,5,9,12,15,17};
    int value=0;
    value = binsearch(v,6,2);
    if(value == -1)
    {
        printf("Element not found\n");
    }
    else
    {
        printf("element number is %d and the value is %d",value, v[value]);
    }
    return 0;
}

if i take the element as 2.

low high mid v[mid]

0 5 (0+5)/2 = 2 9 2 < 9; high = mid+1; high = 2+1 =3
0 3 (0+3)/2 = 1 5 2 < 5; high = mid+1; high = 1+1 =2
0 2 (0+2)/2 = 1 5 2 < 5; high = mid+1; high = 1+1 =2
0 2 (0+2)/2 = 1 5 2 < 5; high = mid+1; high = 1+1 =2

It is going into infinite loop. What iam missing

This question has already been answered. Start a new discussion instead.