qsort

Sorts an array using the quick-sort algorithm

#include <stdlib.h>
void qsort ( void *array , size_t n , size_t size ,
int (*compare )( const void *, const void * ) );

The qsort( ) function sorts the array referenced by its first argument according to a user-definable sorting criterion using the quick-sort algorithm. You determine the sorting criterion by defining a callback function that compares two array elements in some way and indicates which is greater. The qsort( ) function calls this function by the pointer passed in the last argument to qsort( ) each time it needs to compare two elements of the array.

The comparison function takes as its arguments two pointers to elements of the array being sorted. The corresponding parameters are declared as void pointers, so that qsort( ) can be used with any type of array element. The comparison must return a negative value if its first argument is "less than" the second, a positive value if the first argument is "greater than" the second, or zero if they are "equal." It is up to you to define the criteria that constitute these relations for the given type of array element. The qsort( ) function sorts the array in ascending order. The same comparison function can be used by the bsearch( ) function.

#### Example

int strptrcmp( const void *sp1, const void *sp2 );

int main( )
{
char *words[ ] = { "Then",   "he",   "shouted", "What", "I",
"didn't", "hear", "what",    "you",  "said" };

int n = sizeof(words) / sizeof(char *);

qsort( words, n, sizeof(char *), strptrcmp );

for ( int j = 0 ; j < n ; j++ )
puts( words[j] );
}

int strptrcmp( const void *sp1, const void *sp2 )
// Compare two strings by reference.
{
// qsort( ) passes a pointer to the pointer:
// dereference it to pass a char * to strcmp.
const char * s1 = *(char **)sp1;
const char * s2 = *(char **)sp2;
return strcmp( s1, s2 );
}

This program sorts the words in the array in alphabetical order. As the output shows, any capital letter is less than any lowercase letter, and "he" is less than "hear":

I
Then
What
didn't
he
hear
said
shouted
what
you

See also the example for bsearch( ) in this chapter, as well as Example 4-1.