/* simple qsort demo */ #include #include #include int idcomp( const void *p1, const void *p2 ); /* compare id */ int frcomp( const void *p1, const void *p2 ); /* compare fruits */ struct idtable { int id; char *fruits; }; main() { int i, n; struct idtable a[] = { { 32, "banana"}, { 23, "orange"}, { 17, "pine apple"}, { 42, "apple"}, { 13, "lemon"}, { 51, "papaya"}, }; n = sizeof( a ) / sizeof( a[0] ); printf( "Before sorting...\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 */ idcomp ); /* function to compare */ printf( "After sorting by id...\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 */ printf( "After sorting by fruits...\n" ); for( i = 0; i < n; i++ ) printf( "%5d %5d %s\n", i, a[i].id, a[i].fruits ); return( 0 ); } int idcomp( const void *p1, const void *p2 ) { struct idtable *t1, *t2; t1 = (struct idtable *)p1; t2 = (struct idtable *)p2; return t1->id - t2->id; } int frcomp( const void *p1, const void *p2 ) { struct idtable *t1, *t2; t1 = (struct idtable *)p1; t2 = (struct idtable *)p2; return strcmp(t1->fruits, t2->fruits ); }