C Library Functions -qsort()
C Standard Library - <stdlib.h>
Description
qsortis a function provided in the C standard library, used for quicksorting arrays. It is in<stdlib.h>Defined in the header file.qsortIt uses the quicksort algorithm, which is an efficient sorting algorithm with an average time complexity of O(n log n).
C Library Functionsvoid qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) Sort the array.
Declaration
The following is the declaration of the qsort() function.
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));
Parameter
base: Pointer to the first element of the array to be sorted.nitems: The number of elements in the array.size: Size of each element in the array (in bytes).compar: A pointer to a comparison function used to compare two elements. The comparison function should return an integer indicating the result of the comparison:- Less than zero: indicates that the first element is smaller than the second element.
- Equal to zero: indicates that the two elements are equal.
- Greater than zero: indicates that the first element is larger than the second element.
Return Value
This function does not return any value.
Example
The following example demonstrates the usage of the qsort() function.
Example
#include <stdio.h>
#include <stdlib.h>
// define an array containing five integers
int values[] = { 88, 56, 100, 2, 25 };
// comparison function used to compare two integers
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int n;
// output the array contents before sorting
printf(List before sorting:\n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
// use the qsort function to sort the array
qsort(values, 5, sizeof(int), cmpfunc);
// output the array contents after sorting
printf("\nList after sorting:\n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return 0;
}
#include <stdlib.h>
// define an array containing five integers
int values[] = { 88, 56, 100, 2, 25 };
// comparison function used to compare two integers
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int n;
// output the array contents before sorting
printf(List before sorting:\n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
// use the qsort function to sort the array
qsort(values, 5, sizeof(int), cmpfunc);
// output the array contents after sorting
printf("\nList after sorting:\n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return 0;
}
Let us compile and run the above program, which will produce the following result:
排序之前的列表: 88 56 100 2 25 排序之后的列表: 2 25 56 88 100other extensions