qsort() — Sort array

Format

#include <stdlib.h>

void qsort(void *base, size_t num, size_t width,
           int(*compare)(const void *element1, const void *element2));

General description

The qsort() function sorts an array of num elements, each of width bytes in size, where the first element of the array is pointed to by base.

The compare pointer points to a function, which you supply, that compares two array elements and returns an integer value specifying their relationship. The qsort() function calls the comparison function one or more times during the sort, passing pointers to two array elements on each call. The comparison function must compare the elements and return one of the following values:
Value
Meaning
< 0
element1 less than element2
0
element1 equal to element2
> 0
element1 greater than element2

The sorted array elements are stored in increasing order, as returned by the comparison function. You can sort in reverse order by reversing the "greater than" and "less than" logic in the comparison function. If two elements are equal, their order in the sorted array is unspecified. The qsort() function overwrites the contents of the array with the sorted elements.

Returned value

The qsort() function returns no values.

Related information