Mega Code Archive

 
Categories / C / Data Structure Algorithm
 

Binary search

#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; }