qsort() — Sort Array

Format

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

Language Level

ANSI

Threadsafe

Yes

Description

The qsort() function sorts an array of num elements, each of width bytes in size. The base pointer is a pointer to the array to be sorted. The qsort() function overwrites this array with the sorted elements.

The compare argument is a pointer to a function you must supply that takes a pointer to the key argument and to an array element, in that order. The qsort() function calls this function one or more times during the search. The function must compare the key and the element and return one of the following values:

Table 1. Return values of the qsort() compare function
Value Meaning
Less than 0 key less than element
0 key equal to element
Greater than 0 key greater than element

The sorted array elements are stored in ascending order, as defined by your compare function. You can sort in reverse order by reversing the sense of “greater than” and “less than” in compare. The order of the elements is unspecified when two elements compare equally.

Return Value

There is no return value.

Example

This example sorts the arguments (argv) in ascending lexical sequence, using the comparison function compare() supplied in the example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
               /* Declaration of compare() as a function */
int compare(const void *, const void *);
 
int main (int argc, char *argv[ ])
{
   int i;
   argv++;
   argc--;
   qsort((char *)argv, argc, sizeof(char *), compare);
   for (i = 0; i < argc; ++i)
      printf("%s\n", argv[i]);
   return 0;
}
 
int compare (const void *arg1, const void *arg2)
{
               /* Compare all of both strings */
   return(strcmp(*(char **)arg1, *(char **)arg2));
}
 
/***********  If the program is passed the arguments:  ************
******** 'Does' 'this' 'really' 'sort' 'the' 'arguments' 'correctly?'****
****************  then the expected output is: *******************
 
arguments
correctly?
really
sort
the
this
Does
*/

Related Information