Code:
/* bsearch example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort, bsearch, NULL */
int compareints (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int keys[] = {2, 5, 7, 12, 34, 44, 46, 51, 57, 67, 73, 83, 92, 100};
int main ()
{
int * pItem;
int a = 4;
int b = 44;
int c = 46;
int d = 8;
int e = 83;
int f = 100;
int g = 35;
pItem = (int*) bsearch (&a, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",a);
pItem = (int*) bsearch (&b, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",b);
pItem = (int*) bsearch (&c, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",c);
pItem = (int*) bsearch (&d, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",d);
pItem = (int*) bsearch (&e, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",e);
pItem = (int*) bsearch (&f, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",f);
pItem = (int*) bsearch (&g, keys, 14, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",g);
return 0;
}