资源描述:
《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