C stdlib qsort() Function
Example
Sort an array:
// Comparing function:
// Returns a positive number if a is greater than b
// Returns a negative number if a is less than b
// Returns 0 if a is equal to b
int compare(const void *a, const void *b) {
int *valA = a;
int *valB = b;
return *valA - *valB;
}
int main() {
// Create an array
int myArray[] = {20, 32, 5, 2, 24, 15};
int size = sizeof(myArray) / sizeof(myArray[0]);
// Sort the values in the array
qsort (myArray, size, sizeof(myArray[0]), compare);
// Display the values of the array
for(int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}
return 0;
}
Try it Yourself »
Definition and Usage
The qsort()
function sorts the elements in an array from least to greatest.
The qsort()
function is defined in the <stdlib.h>
header file.
Syntax
qsort(void * arr, size_t amount, size_t size, compare);
The size_t
data type is a non-negative integer.
Parameter Values
Parameter | Description |
---|---|
arr | Required. Specifies the array to be sorted. |
amount | Required. Specifies the number of elements in the array. |
size | Required. Specifies the size of an element in the array measured in bytes. |
compare |
Required. Specifies a function used to compare pairs of elements in the array to determine which one is greater. The function should have the structure int myFunction(const void * a, const void * b) where the parameters a and b are pointers to elements in the array being compared.The function should return a positive number if a is greater than b, a negative number if a is less than b and zero if a and b are equal. |