qsort
Defined in header <stdlib.h>
|
||
errno_t qsort_s( void *ptr, rsize_t count, rsize_t size, int (*comp)(const void *, const void *, void *context), |
(since C11) | |
Sorts the given array pointed to by ptr
in ascending order. The array contains count
elements of size
bytes. Function pointed to by comp
is used for object comparison. The context
specifies additional details about the sort.
If comp
indicates two elements as equivalent, their order is undefined.
As with all bounds-checked functions, qsort_s
is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including <stdlib.h>
.
Contents |
Parameters
ptr | - | pointer to the array to sort |
count | - | number of element in the array |
size | - | size of each element in the array in bytes |
comp | - | comparison function which returns a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equivalent. The signature of the comparison function should be equivalent to the following: int cmp(const void *a, const void *b); The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. |
context | - | additional information about the sort (e.g., collating sequence) |
Return value
(none)
Example
The following code sorts an array of integers using qsort()
#include <stdio.h> #include <stdlib.h> int compare_ints(const void* a, const void* b) { int arg1 = *(const int*)a; int arg2 = *(const int*)b; if (arg1 < arg2) return -1; if (arg1 > arg2) return 1; return 0; } int main(void) { int i; int ints[] = { -2, 99, 0, -743, 2, 3, 4 }; int size = sizeof ints / sizeof *ints; qsort(ints, size, sizeof(int), compare_ints); for (i = 0; i < size; i++) { printf("%d ", ints[i]); } printf("\n"); return EXIT_SUCCESS; }
Output:
-743 -2 0 2 3 4 99
References
- C11 standard (ISO/IEC 9899:2011):
- 7.22.5.2 The qsort function (p: 355-356)
- K.3.6.3.2 The qsort_s function (p: 609)
- C99 standard (ISO/IEC 9899:1999):
- 7.20.5.2 The qsort function (p: 319)
- C89/C90 standard (ISO/IEC 9899:1990):
See also
(C11) |
searches an array for an element of unspecified type (function) |
C++ documentation for qsort
|