Parameters
void *field
Pointer to the first element of the array to be sorted.
size_t n
Number of elements to be sorted.
size_t elsize
Size of an element, in bytes.
int (*comp)(const void *, const void *)
Pointer to a function that compares two elements and returns a whole number as its result. This result is interpreted as follows:
Definition | #include <stdlib.h> void qsort(void *field, size_t n, size_t elsize, int (*comp)(const void *, const void *);
| |||||||||
Parameter | void *feld Pointer to the first element of the array to be sorted. size_t n Number of elements to be sorted. size_t elsize Size of an element, in bytes. int (*comp)(const void *, const void *) Pointer to a function that compares two elements and returns a whole number as its result. This result is interpreted as follows:
The function has two parameters, i.e. two pointers to the type of the array elements. The function may be defined something like this: Example 1 /*compares two char values */ int comp(const void *a, const void *b) { if(*((const char *)a) < *((const char *) b) ) return(-1); else if(*((const char *)a) > *((const char *) b ) ) return(1); return(0); } Example 2 /*compares two integer values */ int compare(const void *a, const void *b) { return ( *((const int *) a) - *((const int *) b) ); } | |||||||||
Note | Array elements that are determined to be equal by the comparison function are retained in the same order. | |||||||||
Example | The following program sorts a number field and outputs it on the standard output. #include <stdio.h> #include <stdlib.h> int comp (const void *s, const void *t) { return ( *((const int *) s) - *((const int *) t) ); } int main(void) { int j; static int array[] = {4,7,2,1,54,9,2,3,1,23}; qsort (array, 10, sizeof(int), comp); for (j=0; j<10; j++) printf("%d\n", array[j]); return 0; } | |||||||||
See also | bsearch |