功 能: 使用
快速排序例程进行排序
头文件: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];
}
注意
使用库函数排序的代码量并不比用冒泡排序法小,但速度却快很多。
|