Handout 12b

qsort


 // qsort example

 #include <ctime>
 #include <iostream>
 #include <cstdlib>
 #include <cstring>
 using namespace std;

 #define ITERATIONS 10000
 #define ARRAY_SIZE 50

 // function prototype
 int sort_function( const void * a, const void * b);

 int main(void)
 {
      int long i;
      int j;
      char list[ARRAY_SIZE][2];
      clock_t start, end;

      for(j=0; j<ARRAY_SIZE; j++) list[j][1] ='\0';
      start = clock(); // start the clock
      for(i=0; i<ITERATIONS; i++) {
        for(j=0; j<ARRAY_SIZE; j++) list[j][0] = rand(); // set values
        // sort the values
        qsort((void *)list, ARRAY_SIZE, sizeof(list[0]), sort_function);
      }

      end = clock(); // end the clock

      // display time

      cout << "The elapsed time was: " << (((float) end - start) / CLK_TCK) << " seconds" << endl;


      return 0;
 }

 int sort_function( const void *a, const void *b)
 {

   /* This comparison function must return a negative value if a is less than b, 
      zero if the two are equal, or a positive value if a is greater than b. Two array
      elements that are equal can appear in the sorted array in either order.
   */

      // function required by qsort
      return( strcmp((char *)a,(char *)b) );
 }

Some Notes

The qsort function implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. qsort overwrites this array with the sorted elements. The argument compare is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. qsort calls the compare routine one or more times during the sort, passing pointers to two array elements on each call:

compare( (void *) elem1, (void *) elem2 );


The routine must compare the elements, then return one of the following values:

Return Value  Description


    < 0       elem1 less than elem2
      0       elem1 equivalent to elem2
    > 0       elem1 greater than elem2

Call

void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );

Parameters

base - Start of target array
num- Array size in elements
width - Element size in bytes
compare - Comparison function

elem1- Pointer to the key for the search
elem2 - Pointer to the array element to be compared with the key