#import <Foundation/Foundation.h>
//创建一个学生变量
typedef struct student{
char name[20]; //姓名
int age; //年龄
float weight; //体重
float height; //身高
float score; //分数
}Stu;
//为什么使用动态排序,动态排序的好处:所有的排序函数if语句之后的比较条件不一样,其余的所有代码都是相同的,把相同的内容放在一个函数里,只写一遍即可,把if语句后面不同条件写个一个个的条件函数 以供回调即可,
BOOL sortStudentByAge(Stu stu1,Stu stu2);
BOOL sortStudentByAge(Stu stu1,Stu stu2){
return stu1.age > stu2.age;
}
//根据体重判定
BOOL sortStudentByWeight(Stu stu1,Stu stu2);
BOOL sortStudentByWeight(Stu stu1,Stu stu2){
return stu1.weight > stu2.weight;
}
//根据身高判定
BOOL sortStudentByHeight(Stu stu1,Stu stu2);
BOOL sortStudentByHeight(Stu stu1,Stu stu2){
return stu1.height > stu2.height;
}
//根据分数判定
BOOL sortStudentByScore(Stu stu1,Stu stu2);
BOOL sortStudentByScore(Stu stu1,Stu stu2){
return stu1.score > stu2.score;
}
typedef BOOL(*SORT)(Stu,Stu);//重定义
void sortStudent(Stu *p,int count,SORT p2){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - 1 - i; j++) {
//函数指针调用相应的函数
if (p2(*(p + j),*(p + j + 1))) {
Stu temp = *(p + j);
*(p + j) = *(p + j + 1);
*(p + j + 1) = temp;
}
}
}
}
//输出排序后学生的顺序
void printAllSortStudent(Stu *p,int count){
for (int i = 0; i < count; i++) {
printf("姓名:%s 年龄:%d 体重:%.2f 身高:%.2f 分数:%.2f \n",(p + i) -> name,(p + i) -> age,(p + i) -> weight,(p + i) -> height,(p + i) -> score);
}
}
int main(int argc, const char * argv[]) {
Stu stus[5] ={
{"HaiFeng",21,130,175,89},
{"ShiYang",12,190,155,18},
{"YaNan " , 38,90,200,60},
{"JangTao",49,49,188,99},
{"XiaoLong",5,30,160,100}
};
sortStudent(stus, 5, sortStudentByHeight);
printf("按照身高排序好的学生的顺序:\n");
printAllSortStudent(stus, 5);
sortStudent(stus, 5, sortStudentByWeight);
printf("按照体重排序好的学生的顺序:\n");
printAllSortStudent(stus, 5);
sortStudent(stus, 5, sortStudentByAge);
printf("按照年龄排序好的学生的顺序:\n");
printAllSortStudent(stus, 5);
sortStudent(stus, 5, sortStudentByScore);
printf("按照分数排序好的学生的顺序:\n");
printAllSortStudent(stus, 5);
return 0;
}