共有回帖数 0 个
-
编译器函数库自带的快速排序函数。使用qsort()排序并用 bsearch()搜索是一个比较常用的组合,使用方便快捷。qsort 的函数原型是void qsort(void*base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));
函数简介 编辑
功 能: 使用快速排序例程进行排序头文件:stdlib.h用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));参数: 1 待排序数组首地址2 数组中待排序元素数量3 各元素的占用空间大小4 指向函数的指针,用于确定排序的顺序
用法 编辑
1 其中base是排序的一个集合数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。比如:对一个长为1000的数组进行排序时,int a[1000]; 那么base应为a,num应为 1000,width应为 sizeof(int),comp函数随自己的命名。qsort(a,1000,sizeof(int),comp);其中comp函数应写为:1234int comp(const void*a,const void*b){return *(int*)a-*(int*)b;}上面是由小到大排序,return *(int *)b - *(int *)a; 为由大到小排序。MSDN:The qsort function implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. qsort overwrites this array with the sorted elements. The argument compare is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. qsort calls the compare routine one or more times during the sort, passing pointers to two array elements on each call:以下为compare函数原型 //compcompare( (void *) & elem1, (void *) & elem2 );Compare 函数的返回值描述 0elem1将被排在elem2前面0elem1 等于 elem2 0elem1 将被排在elem2后面对一维数组的排序实例(从小到大排序):123456789101112131415161718192021222324#includestdio.h#includestdlib.hint comp(const void*a,const void*b){return *(int*)a-*(int*)b;}int main(){int *array;int n;scanf("%d",&n);array=(int*)malloc(n*sizeof(int));int i=0;for(;in;i++){scanf("%d",(array+i));}qsort(array,n,sizeof(int),comp);for(i=0;in;i++){printf("%dt",array);}return0;}对一个二维数组进行排序:int a[1000][2]; 其中按照a[0]的大小进行一个整体的排序,其中a[1]必须和a[0]一起移动交换。//即第一行和第二行(a[0]和a[1]分别代表第一行和第二行的首地址)。使用库函数排序的代码量并不比用冒泡排序法小,但速度却快很多。



楼主 2015-12-10 14:01 回复
Copyright © 2010~2015 直线网 版权所有,All Rights Reserved.沪ICP备10039589号
意见反馈 |
关于直线 |
版权声明 |
会员须知