一、《C语言函数库》对qsort的说明(p110)
qsort:快速排序函数
函数原型:void qsort(void *base, int nelem, int width, int(*fcmp)(const void *, const *))
头文件 :#include<stdlib.h>
是否是标准函数:是
函数功能:对记录 进行从小到大的快速排序。参数base指向存放待排序列的数组的首地址,nelem为数组中元素的个数,width为每个元素的字节数,int(*fcmp)(const void *, const *)为由用户提供的比较函数。
返回值:无
二、简单例子
/* C中qsort函数的使用 */
#include<stdio.h>
#include<stdlib.h>
int CMP(const void * a ,const void * b){//特别注意1
return *(int *)a-*(int *)b;
}
int main()
{
int sort[10]={3,2,6,12,1,7,-5,9,30,16};
int i;
printf("\nThe array that is before sort \n");
for(i=0;i<10;i++){
printf("%d ",sort[i]);
}
qsort(sort,10,sizeof(int),CMP);//特别注意2
printf("\nThe array that is after sort\n");
for(i=0;i<10;i++){
printf("%d ",sort[i]);
}
printf("\n");
return 0;
}
三、特别注意
1.qsort第四个参数,即上例中的函数cmp,返回值必须是int,两个参数的类型必须都是const void *类型,因此在写比较复杂的比较函数时,可提前先进行强制类型转换,转换成相应的类型;
2.对于书中提供的例子编译通不过,也有另一种解决方法,即在调用时直接进行强制类型转换,即将上述两处分别更改为
int CMP(int * a ,int * b){//特别注意1
qsort(sort,10,sizeof(int), (int (*)(const void *, const void *)) CMP);//特别注意2
一般使用第一种方法。
四、其他类型的比较函数的书写
1.字符串的比较,直接使用 strcmp函数;
/* C中qsort函数的使用 */
//字符串数组的比较
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int CMP(const void* a ,const void * b){//特别注意1
return strcmp((char*)a,(char *)b);
}
int main()
{
char list[5][4]={"cat","car","cab","cap","can"};
int i;
qsort(list,5,sizeof(list[0]), CMP);//特别注意2
for(i=0;i<5;i++){
printf("%s\n",list[i]);
}
return 0;
}
2.结构体的比较
见http://blog.csdn.net/lonely_fish/article/details/18940561
此外补充,结构体的用法:
struct是结构体的关键字,用来声明结构体变量如
struct student
{ char num[10];
char name[20];
int age;
};
struct student stu[10]来声明一个结构体数组
typedef是用来定义新的类型名来代替已有的类型名,
可将上面的结构体定义为
typedef struct student
{ char num[10];
char name[20];
int age;
}student;
也就是说,将原来的struct student 重新定义为 stud;
可以直接用 student stu[10]来声明一个结构体数组