qsort() – C语言库函数
C库函数 void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) 数组进行排序。
声明
以下是声明 qsort() 函数。
void qsort(void*base,size_t nitems,size_t size,int(*compar)(constvoid*,constvoid*))
参数
-
base -- 这就是指针的数组的第一个元素进行排序。
-
nitems -- 这是由基部指向的数组中的元素数目。
-
size -- 这是在数组中的每个元素的大小(以字节为单位)。
-
compar -- 这个函数比较两个元素。
返回值
这个函数不返回任何值。
例子
下面的例子显示的 qsort() 函数的用法。
#include<stdio.h>#include<stdlib.h>int values[]={88,56,100,2,25};int cmpfunc (constvoid* a,constvoid* b){return(*(int*)a -*(int*)b );}int main(){int n; printf("Before sorting the list is: ");for( n =0; n <5; n++){ printf("%d ", values[n]);} qsort(values,5,sizeof(int), cmpfunc); printf(" After sorting the list is: ");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