C语言标准库函数qsort详解

C语言标准库函数qsort详解

ID:40533360

大小:31.00 KB

页数:4页

时间:2019-08-04

C语言标准库函数qsort详解_第1页
C语言标准库函数qsort详解_第2页
C语言标准库函数qsort详解_第3页
C语言标准库函数qsort详解_第4页
资源描述:

《C语言标准库函数qsort详解》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、C语言标准库函数qsort详解qsort包含在头文件中,此函数根据你给的比较条件进行快速排序,通过指针移动实现排序。排序之后的结果仍然放在原数组中。使用qsort函数必须自己写一个比较函数。函数原型:voidqsort(void*base,size_tnum,size_tsize,int(*comparator)(constvoid*,constvoid*));用法以及参数说明:Sortsthenumelementsofthearraypointedbybase,eachelementsizebyteslong,usingthec

2、omparatorfunctiontodeterminetheorder.Thesortingalgorithmusedbythisfunctioncomparespairsofvaluesbycallingthespecifiedcomparatorfunctionwithtwopointerstoelementsofthearray.Thefunctiondoesnotreturnanyvalue,butmodifiesthecontentofthearraypointedbybasereorderingitselementstothenewly

3、sortedorder.basePointertothefirstelementofthearraytobesorted.(数组起始地址)numNumberofelementsinthearraypointedbybase.(数组元素个数)sizeSizeinbytesofeachelementinthearray.(每一个元素的大小)comparatorFunctionthatcomparestwoelements.(函数指针,指向比较函数)1、Thefunctionmustaccepttwoparametersthatarepointerstoe

4、lements,type-castedasvoid*.Theseparametersshouldbecastbacktosomedatatypeandbecompared.2、Thereturnvalueofthisfunctionshouldrepresentwhetherelem1isconsideredlessthan,equalto,orgreaterthanelem2byreturning,respectively,anegativevalue,zeroorapositivevalue.ReturnValuenone(无返回值)一、对int

5、类型数组排序intnum[100];intcmp(constvoid*a,constvoid*b){return*(int*)a-*(int*)b;}qsort(num,100,sizeof(num[0]),cmp);二、对char类型数组排序(同int类型)charword[100];intcmp(constvoid*a,constvoid*b){return*(char*)a-*(int*)b;}qsort(word,100,sizeof(word[0]),cmp);三、对double类型数组排序doublein[100];intcmp(cons

6、tvoid*a,constvoid*b){return*(double*)a>*(double*)b?1:-1;}qsort(in,100,sizeof(in[0]),cmp);四、对结构体一级排序structSample{doubledata;intother;}s[100]//按照data的值从小到大将结构体排序intcmp(constvoid*a,constvoid*b){return(*(Sample*)a).data>(*(Sample*)b).data?1:-1;}qsort(s,100,sizeof(s[0]),cmp);五、对结构体二

7、级排序structSample{intx;inty;}s[100];//按照x从小到大排序,当x相等时按照y从大到小排序intcmp(constvoid*a,constvoid*b){structSample*c=(Sample*)a;structSample*d=(Sample*)b;if(c->x!=d->x)returnc->x-d->x;elsereturnd->y-c->y;}qsort(s,100,sizeof(s[0]),cmp);六、对字符串进行排序structSample{intdata;charstr[100];}s[100];/

8、/按照结构体中字符串str的字典顺序排序intcmp(constvoid*a,constvoid*b){re

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。