[Previous]
[Contents]
[Next]

qsort()

sort an array, using a modified Quicksort algorithm

Synopsis:

#include <stdlib.h>
void qsort( void *base,
            size_t num,
            size_t width,
            int (*compar) ( const void *, 
                            const void *) );

Description:

The qsort() function sorts an array of num elements, which is pointed to by base, using a modified version of Sedgewick's Quicksort algorithm. Each element in the array is width bytes in size. The comparison function pointed to by compar is called with two arguments that point to elements in the array. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is less than, equal to, or greater than the second argument, respectively.

The version of the Quicksort algorithm employed was proposed by Jon Louis Bentley and M. Douglas McIlroy in the article "Engineering a sort function" published in Software - Practice and Experience, 23(11):1249-1265, November 1993.

Examples:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *CharVect[] = { "last", "middle", "first" };

int compare( const void *op1, const void *op2 )
  {
    const char **p1 = (const char **) op1;
    const char **p2 = (const char **) op2;
    return( strcmp( *p1, *p2 ) );
  }

int main( void )
  {
    qsort( CharVect, sizeof(CharVect)/sizeof(char *),
      sizeof(char *), compare );
    printf( "%s %s %s\n",
        CharVect[0], CharVect[1], CharVect[2] );
    return( EXIT_SUCCESS );
  }

produces the output:

first last middle

Classification:

ANSI

Safety:
Interrupt handler No
Signal handler Read the Caveats
Thread Read the Caveats

Caveats:

This function is signal-handler-safe and thread-safe only if the comparison function pointed to by compar is, too.

See also:

bsearch()


[Previous]
[Contents]
[Next]