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, POSIX, XPG4
qsort sorts an array of num elements, each of width
bytes in size. The base pointer is a pointer to the
array to be sorted. qsort 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. qsort 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:
| 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));
/*********************************************************************
Assuming command line of: qsort kent theresa andrea laura brenden
Output should be:
andrea
brenden
kent
laura
theresa
*********************************************************************/
}
![]()
bsearch -- Search Arrays
![]()
lfind - lsearch -- Find Key in Array
![]()
<search.h>
<stdlib.h>