c语言中的库函数:qsort(int *base,int num,int width,int (*compare)(int *void,int *void));
其中base是排序的一个集合数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。
比如:对一个长为1000的数组进行排序时,int a[1000]; 那么base应为a,num应为 1000,width应为 sizeof(int),comp函数随自己的命名。
qsort(a,1000,sizeof(int),comp);
其中comp函数应写为:
1
2
3
4
|
intcomp(constvoid*a,constvoid*b)
{
return
*(
int
*)a-*(
int
*)b;
}
|
上面是由小到大排序,return *(int *)b - *(int *)a; 为由大到小排序。
举一个例子:对一个结构体中的分数进行排序,结构体的成绩是随机数生成的,学生学号和姓名是从控制台输入的。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/*
测试数据:
001 zhang
002 zhao
003 masan
004 zhaoyun
005 wangqi
006 zhaodan
007 maowanli
008 zhengping
009 bingbing
010 zhahao
*/
struct StuInfo
{
char sno[20];
char name[20];
float score;
};
int p(const void *left, const void *right)
{
struct StuInfo *stu1 = (struct StuInfo *)left;
struct StuInfo *stu2 = (struct StuInfo *)right;
if (stu1->score > stu2->score){
return -1;
}
else{
return 1;
}
}
void structSort()
{
struct StuInfo stu[10], temp;
srand(time(NULL));
int i = 0, j = 0, k = 0;
printf("Please input 10 students' infomation(sno,name):\n");
for (i = 0; i < 10; ++i){
scanf("%s %s",stu[i].sno,stu[i].name);
stu[i].score = rand()%200/2.0;
}
/*库函数排序*/
qsort(stu, 10, sizeof(struct StuInfo), p);
printf("The student infomation from high to low.\n");
for (i = 0; i < 10; ++i)
printf("%5s,%10s,%5.2f\n",stu[i].sno,stu[i].name,stu[i].score);
}
int main()
{
structSort();
return 0;
}