Q

Top  Previous  Next
qsort

#include <stdlib.h>

void qsort (

   void   *base,

   size_t  nmemb,

   size_t  size,

   int   (*compar) (const void *, const void *)

);

stand-alone

stack: potentially large

This function sorts an array of items into ascending order. The array of items is pointed to by base; in the array, there are nmemb elements, with each element in the array being size octets (eight-bit bytes) long.

 

Note that the type of the elements in the array is completely general: it might be int in a simple program or some complex struct type in a more sophisticated program.

 

The definition of 'ascending order' for this arbitrary data type is provided by the function compar that is passed to qsort as a parameter. The function pointed to by compar takes two arguments, each a pointer to an item of the type that makes up the array pointed to by base. The function returns an integer less than, equal to, or greater than, zero according to whether the object pointed to by its first argument is to be regarded as less than, equal to, or greater than, that pointed to by its second argument.

 

For example, the following function could be used as a comparison function when it is desired to sort an array of doubles into ascending order:

 

static int compare_doubles(const void *v1, const void *v2) {

   double *d1 = (double *)v1, *d2 = (double *)v2;

   if (*d1 < *d2) return -1// less

   if (*d1 > *d2) return 1;  // greater

   return 0;                 // equal

}

 

The corresponding call on qsort might be as follows, assuming an array a of 1000 doubles:

 

qsort(a, 1000sizeof(double), compare_doubles);

 

Although qsort nominally sorts the array into ascending order, it can sort into any desired order by appropriate choice of the function passed as the compar argument. The array of doubles used in the previous example could have been sorted into descending order of absolute value using the following comparison function:

 

#include <math.h>

int compare_abs_doubles(const void *v1, const void *v2) {

double *d1 = (double *)v1;

double *d2 = (double *)v2;

if (fabs(*d1) < fabs(*d2)) return 1;  // less => more

if (fabs(*d1) > fabs(*d2)) return -1// more => less

return 0;

}

 

Here, fabs has been used to get the absolute value of the variables pointed to by each argument. The sign of the return value is opposite from that in the previous example to give the effect of reversing the order in which qsort sorts the array.

 

Once an array has been sorted into the correct order using qsort, the function bsearch can be used to search for a particular element within the array.

 

It is not usually advisable to code the compar function as follows, for example:

 

return *d1 - *d2;

 

This is because in some circumstances there could be an overflow, resulting in the items being sorted wrongly.