/* simple bsearch demo */ #include #include #include int frcomp( const void *p1, const void *p2 ); /* compare fruits */ struct idtable { int id; char *fruits; }; main() { int i, n; char *key; struct idtable *result; struct idtable a[] = { { 32, "banana"}, { 23, "orange"}, { 17, "pine apple"}, { 42, "apple"}, { 13, "lemon"}, { 51, "papaya"}, }; n = sizeof( a ) / sizeof( a[0] ); printf( "Data is...\n" ); for( i = 0; i < n; i++ ) printf( "%5d %5d %s\n", i, a[i].id, a[i].fruits ); qsort( a, /* address of array to be sorted */ n, /* number of elements in array */ sizeof( a[0] ), /* size of an element */ frcomp ); /* function to compare */ key = "apple"; result = (struct idtable *)bsearch( key, /* address of key element */ a, /* address of array to be searched */ n, /* number of elements in array */ sizeof(a[0]), /* size of an element */ frcomp); /* function to compare */ if (result == NULL) printf("Not found.\n"); else printf("Found: %5d %s\n", result->id, result->fruits); return( 0 ); } int frcomp( const void *p1, const void *p2 ) { struct idtable *t2; t2 = (struct idtable *)p2; return strcmp((char *)p1, t2->fruits ); }