/* simple qsort demo */ #include #include #include int comp( const void *p1, const void *p2 ); /* function to compare for qsort */ main() { int i, n; char *a[] = { "banana", "orange", "pine apple", "apple", "lemon", "papya", }; char *key, **result; n = sizeof( a ) / sizeof( a[ 0 ] ); printf( "Data is...\n" ); for( i = 0; i < n; i++ ) printf( "%5d %5s\n", i, a[ i ] ); qsort( a, /* address of array to be sorted */ n, /* number of elements in array */ sizeof( a[0] ), /* size of an element */ comp ); /* function to compare */ key = "apple"; result = (char **)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 */ comp); /* function to compare */ if (result == NULL) printf("Not found.\n"); else printf("Found: %s\n", *result); return( 0 ); } int comp( const void *p1, const void *p2 ) { return strcmp( (char *)p1, *(char **)p2 ); }