Table of Content

Added test driver to binsearch function which comes from K&R C.

#include <stdio.h>
#include <string.h>

int binsearch(int x,int v[],int n);

/* test binsearch function */
main()
{
    int x1 = 8;
    int v1[10] = {4,2,5,6,8,2,34,12,23,10};

    int index = binsearch(x1,v1,10);
    printf("v1[] =");

    int i;
    for (i=0;i<10;i++)
        printf(" %d", v1[i]);
    printf("\nThe index of number %d in v1[]: %d\n",x1,index);
    return 0;
}

/* 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 */
}

test result:

$ binsearch
v1[] = 4 2 5 6 8 2 34 12 23 10
The index of number 8 in v1[]: 4