/* qsortex.c By Jeff Ondich, 1/22/97 Example of how to use the qsort() library function. Also, how to call a function that's passed to you as a parameter (see the calling() function below). */ #include #include #include #define MAX 10 int compare( const void *a, const void *b ); void calling( int (*cmp)( const void *, const void * ) ); void main(void) { int i, key[MAX]; /* Set up a random array of integers, and print them */ srandom( time(NULL) ); for( i=0; i < MAX; i++ ) { key[i] = random() % MAX; printf( "%d ", key[i] ); } printf( "\n" ); /* Sort them and print the resulting list */ qsort( key, MAX, sizeof(int), compare ); for( i=0; i < MAX; i++ ) { printf( "%d ", key[i] ); } printf( "\n" ); /* Demonstrate how a function calls another function that's passed to it as an argument. */ printf( "And now to try calling a passed function:\n" ); calling( compare ); } int compare( const void *a, const void *b ) { return( *((int *)a) - *((int *)b) ); } void calling( int (*thefunction)( const void *, const void * ) ) { int p=1, q=2; if( (*thefunction)(&p,&q) > 0 ) printf( "1 > 2\n" ); else printf( "1 <= 2\n" ); }