C Library Functions - qsort ()
C standard library - <stdlib.h>
description
C library functionsvoid qsort (void * base, size_t nitems, size_t size, int (* compar) (const void *, const void *)) to sort the array.
statement
Here is the qsort () function's declaration.
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
parameter
- base - a pointer to the first element of the array to be sorted.
- nitems - the number of points to the base of the array elements.
- size - the size of each element in the array, in bytes.
- compar - function used to compare two elements.
return value
This function does not return a value.
Examples
The following example demonstrates the qsort () function is used.
#include <stdio.h> #include <stdlib.h> int values[] = { 88, 56, 100, 2, 25 }; int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { int n; printf("排序之前的列表:\n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } qsort(values, 5, sizeof(int), cmpfunc); printf("\n排序之后的列表:\n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } return(0); }
Let's compile and run the above program, which will result in the following:
排序之前的列表: 88 56 100 2 25 排序之后的列表: 2 25 56 88 100