Binary search:bsearch in stdlib.h : Search « Data Structure Algorithm « C / ANSI-C






Binary search:bsearch in stdlib.h



#include <stdio.h>
#include <stdlib.h>

int values[] = { 1 , 2 , 3, 4 , 9 , 10 };

int compare (const void * a, const void * b) {
  return ( *(int*)a - *(int*)b );
}

int main ()
{
  int *pos;
  int key = 9;
  
  pos = (int*) bsearch (&key, values, 6, sizeof (int), compare);
  
  if ( pos != NULL )
    printf ("%d is in the array", *pos);
  else
    printf ("%d is not in the array", key);
  
  return 0;
}

           
       








Related examples in the same category

1.The Binary search