使用VC库函数中的快速排序函数

来源:互联网 发布:淘宝免费流量 编辑:程序博客网 时间:2024/05/22 03:10

上一篇讲了快速排序的实现。但在很多场合,直接使用快速排序的库函数是很方便的。下面讲下VC中库函数qsort()的用法:http://blog.csdn.net/morewindows/article/details/6684561

函数原型:

void qsort(void *base,size_t num,size_t width, int (__cdecl *compare )(const void *, const void *) );

第一个是数组地址,第二是数组大小,第三个是数组中每个元素的字节数,最后一个是个函数指针,表示如何比较数组中的元素。

头文件 #include <stdlib.h>

下面分别就int等整数数据,double等浮点数据,结构体和类,按指定方式这四种情况进行讲解。

实例1   对int等整数数据进行排序

int cmp(const void *x, const void *y){return *(int*)x - *(int*)y;}qsort(a, MAXN, sizeof(a[0]), cmp); 

MAXN为数组大小,下同

实例2   对double等浮点数进行排序

 

MAXN为数组大小,下同

实例2   对double等浮点数进行排序

int cmpDouble(const void *x, const void *y){return (*(double*)x > *(double*)y ? 1 : -1);}qsort(a, n, sizeof(a[0]), cmpDouble);


 

实例3  对结构体,类等复杂数据进行排序

struct Student{char szName[30];int  nAge;};


先对年龄排序,年龄相同再按姓名排序。

int cmpStudent (const void *x, const void *y){   //先作下指针转换,再按要求比较Student *pNodex = (Student*)x, *pNodey = (Student*)y;if (pNodex->nAge != pNodey->nAge)return pNodex->nAge - pNodey->nAge;elsereturn strcmp(pNodex->szName, pNodey->szName);}qsort(a, n, sizeof(a[0]), cmpStudent);


 

实例4     按指定方式进行排序。

如对只有大小写字母的字符串"AajkuKdYUBCDwyz"进行排序,要求大写字母在前,小写字母在后。

int cmp1(const void *x, const void *y){char *pcx = (char*)x, *pcy = (char*)y;bool flag1 = *pcx >= 'A' && *pcx <= 'Z';bool flag2 = *pcy >= 'A' && *pcy <= 'Z';if(flag1 == flag2)    //如果都为大写字母或都为小写字母return *pcx - *pcy;else                  //否则,谁为大写字母,谁的权值小。return flag1 ? -1 : 1;}int main(){char szText[] = "AajkuKdYUBCDwyz";qsort(szText, strlen(szText), sizeof(szText[0]), cmp1);printf("%s\n", szText);return 0;}


 

 

完整的代码如下:

int cmp(const void* x,const void* y){return *(int*)x-*(int*)y;}int cmp1(const void* x,const void* y){return *(double*)x>*(double*)y?1:-1;}struct Student{char szName[30];int nAge;};//字节对齐 占用了36个字节 struct Student Stu[10]; sizeof(Stu)共占用36*10个字节int cmp2(const void* x,const void* y){Student* pNodex=(Student*)x,*pNodey=(Student*)y;if(pNodex->nAge!=pNodey->nAge)return pNodex->nAge-pNodey->nAge;elsereturn strcmp(pNodex->szName,pNodey->szName);}int main(void){struct Student Stu[10];for(int i=0;i<10;i++){Stu[i].nAge=i;strcpy(Stu[i].szName,"miao");}swap(Stu[0],Stu[3]);strcpy(Stu[4].szName,"abc");cout<<sizeof(Stu)<<endl;cout<<sizeof(struct Student)<<endl;qsort(Stu,10,sizeof(struct Student),cmp2);for(int i=0;i<10;i++){cout<<Stu[i].szName<<" "<<Stu[i].nAge<<endl;}cout<<endl;}