问题描述
- C语言qsort函数怎么用?
-
#include
using namespace std;typedef struct
{
unsigned long id;
int score;
}record;int main()
{
int id_cmp(const void* s1,const void* s2);
int score_cmp(const void* s1,const void* s2);record recordset[] = {{3,99},{5,87},{4,56},{2,100},{1,17}}; int recordcount = sizeof(recordset) / sizeof(record); printf("排序前:n"); for(int i = 0; i < recordcount;i++) printf("%8d %8u %8dn",i,recordset[i].id,recordset[i].score); qsort(recordset,recordcount,sizeof(record),id_cmp); printf("排序后:n"); for(int i = 0; i < recordcount;i++) printf("%8d %8u %8dn",i,recordset[i].id,recordset[i].score); qsort(recordset,recordcount,sizeof(record),score_cmp); printf("排序后:n"); for(int i = 0; i < recordcount;i++) printf("%8d %8u %8dn",i,recordset[i].id,recordset[i].score); return 0;
}
int id_cmp(const void* s1,const void* s2)
{
record* p1 = (record* )s1;
record* p2 = (record* )s2;
if(p1->id < p2->id) return -1;
else if(p1->id == p2->id) return 0;
else return 1;
}int score_cmp(const void* s1,const void* s2) //这个函数指针为什么能改变排序顺序
{
record* p1 = (record* )s1;
record* p2 = (record* )s2;
if(p1->score < p2->score) return -1;
else if(p1->score == p2->score) return 0;
else return 1;
}
解决方案
因为排序的关键是对要排序的数据两两比较大小,比较大小的不同决定了排序依据的不同,传入不同的函数指针,实现不同的大小比较就能改变排序顺序。
解决方案二:
sort也能进行排序,比如对数组a,从1号单元到n号单元排序,排序函数cmp,sort(a+1,a+1+n,cmp);就结束了。