qsort

Syntax:

    #include <cstdlib>
    void qsort( void *buf, size_t num, size_t size, int (*compare)(const void*, const void *) );

The qsort function sorts buf (which contains num items, each of size size) using Quicksort. The compare function is used to compare the items in buf, and should return negative if the first argument is less than the second, zero if they are equal, and positive if the first argument is greater than the second. qsort() sorts buf in ascending order.

For example, the following bit of code uses qsort to sort an array of integers:

   int compare_ints( const void* a, const void* b ) {  // compare function
     int* arg1 = (int*) a;
     int* arg2 = (int*) b;
     if( *arg1 < *arg2 ) return -1;
     else if( *arg1 == *arg2 ) return 0;
     else return 1;
   }
 
   int array[] = { -2, 99, 0, -743, 2, 3, 4 };
   int array_size = 7;
 
   ...
 
   printf( "Before sorting: " );
   for( int i = 0; i < array_size; i++ ) {
     printf( "%d ", array[i] );
   }
   printf( "\n" );
 
   qsort( array, array_size, sizeof(int), compare_ints );
 
   printf( "After sorting: " );
   for( int i = 0; i < array_size; i++ ) {
     printf( "%d ", array[i] );
   }
   printf( "\n" );

When run, this code displays the following output:

   Before sorting: -2 99 0 -743 2 3 4
   After sorting: -743 -2 0 2 3 4 99

Related Topics: bsearch, sort