使用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;}
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- 使用VC库函数中的快速排序函数
- [编程珠玑读书笔记]最好的快速排序与库函数中的排序函数比较
- 快速排序库函数qsort的使用
- c语言库函数 qsort(快速排序函数)
- 如何利用C语言中的qsort库函数实现快速排序?
- 如何利用C语言中的qsort库函数实现快速排序
- C语言库函数中的排序和查找函数
- Java使用库函数排序
- VC中的SendMessage函数使用
- 快速排序中的partition函数详解
- hdu 1164(一个数的素数因子)
- Project Euler problem 1
- 超链接点击无效的实现方式
- 模拟退火算法解决函数优化问题
- 兔子出生问题(20次)JAVA
- 使用VC库函数中的快速排序函数
- 给IT新人的15个建议:程序员的反省与总结
- 程序员的七大坏毛病
- libevent源码阅读笔记(三)
- 面向过程的软件设计
- 关于informix数据库使用dbexport和dbimport、备份和恢复数据的一点说明
- ASP.NET 服务程序的发布
- C++虚函数及虚函数表解析
- 如何让ie加载特殊的css