Name

qsort

Synopsis

Sorts an array using the quick-sort algorithm

#include <stdlib.h>
voidqsort( 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 ...

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.