void qsort(void *base, size
优质
小牛编辑
143浏览
2023-12-01
描述 (Description)
C库函数void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))对数组进行排序。
声明 (Declaration)
以下是qsort()函数的声明。
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
参数 (Parameters)
base - 这是指向要排序的数组的第一个元素的指针。
nitems - 这是base指向的数组中的元素数。
size - 这是数组中每个元素的大小(以字节为单位)。
compar - 这是比较两个元素的函数。
返回值 (Return Value)
此函数不返回任何值。
例子 (Example)
以下示例显示了qsort()函数的用法。
#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("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
让我们编译并运行上面的程序,它将产生以下结果 -
Before sorting the list is:
88 56 100 2 25
After sorting the list is:
2 25 56 88 100