Mega Code Archive

 
Categories / C / Code Snippets
 

Binary searchbsearch in stdlib.h

#include <stdio.h> #include <stdlib.h> int values[] = { 3 , 2 , 8, 4 , 2 , 9}; 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; }