#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 %8d\n",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 %8d\n",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 %8d\n",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;
}
因為排序的關鍵是對要排序的數據兩兩比較大小,比較大小的不同決定了排序依據的不同,傳入不同的函數指針,實現不同的大小比較就能改變排序順序。