CKTIS / C
qsort — sorting an array
qsort sorts an array using a comparison function that determines the ordering of its elements.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));qsort from <stdlib.h> modifies the array and returns nothing. base points to the first element, nmemb is the element count, and size is one element's size in bytes.
compar receives pointers to elements. It returns a negative value, zero, or a positive value for less, equal, or greater, respectively. It must define a consistent total ordering and must not modify elements.
Equal elements have unspecified order. The standard does not require quicksort. In the example, (a > b) - (a < b) avoids the overflow possible with a - b.
Examples
#include <stdio.h>
#include <stdlib.h>
static int compare_ints(const void *left, const void *right)
{
const int a = *(const int *)left;
const int b = *(const int *)right;
return (a > b) - (a < b);
}
int main(void)
{
int values[] = {4, -2, 4, 0, 1};
const size_t count = sizeof values / sizeof values[0];
qsort(values, count, sizeof values[0], compare_ints);
for (size_t i = 0; i < count; ++i) {
printf("%s%d", i == 0 ? "" : " ", values[i]);
}
putchar('\n');
return 0;
}
Result
-2 0 1 4 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.