qsort的使用

功 能: 使用 快速排序例程进行排序
头文件:stdlib.h
用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
参数: 1 待排序 数组首地址
2 数组中待排序元素数量
3 各元素的占用空间大小
4 指向函数的 指针,用于确定排序的顺序
使用qsort()排序并用 bsearch()搜索是一个比较常用的组合,使用方便快捷。
qsort 的函数原型是void __cdecl qsort (void *base, size_tnum,size_t width,int (__cdecl *comp)(const void *,const void*))
其中base是排序的一个集合 数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。
比如:对一个长为1000的 数组进行排序时,int a[1000]; 那么base应为a,num应为 1000,width应为 sizeof(int),comp函数随自己的命名。
qsort(a,1000,sizeof(int),comp);
其中comp函数应写为:
?
1
2
3
4
intcomp(constvoid*a,constvoid*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函数原型 //comp
compare( (void *) & elem1, (void *) & elem2 );
Compare 函数的返回值
描述
< 0
elem1将被排在elem2前面
0
elem1 等于 elem2
> 0
elem1 将被排在elem2后面
对一个 二维数组进行排序:
int a[1000][2]; 其中按照a[0]的大小进行一个整体的排序,其中a[1]必须和a[0]一起移动交换。
?
1
2
3
4
5
6
7
8
9
10
11
12
qsort (a,1000, sizeof ( int )*2,comp);
  
intcomp(constvoid*a,constvoid*b)
  
{
return (( int *)a)[0]-(( int *)b)[0];
}
  
  
注意
  
使用库函数排序的代码量并不比用冒泡排序法小,但速度却快很多。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值