Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdlib.h>
void qsort(void *base, size_t num, size_t width,
int(*compare)(const void *element1, const void *element2));
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 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.
Special behavior for C++: C++ and C linkage conventions are incompatible, and therefore the qsort() function cannot receive C++ function pointers. If you attempt to pass a C++ function pointer to the qsort() function, the compiler will flag it as an error. To use the C++ qsort() function, you must ensure that the comparison function has C linkage, by declaring it as extern "C".
The qsort() function returns no values.
⁄* CELEBQ01
This example sorts the arguments (argv) in ascending sequence, based on
the ASCII value of each character and string, and using the comparison
function compare() supplied in the example.
*⁄
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
⁄* Declaration of compare() as a function *⁄
#ifdef __cplusplus
extern "C" int compare(const void *, const void *);
#else
int compare(const void *, const void *); ⁄* macro is automatically *⁄
#endif ⁄* defined by the C++⁄MVS compiler *⁄
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));
}
Output
Does, this, really, sort, the, arguments, correctly?
then
expect the following output. arguments
correctly?
really
sort
the
this
Does