首页 > 编程语言 > 详细

利用动态排序,对学生结构体的各类信息进行排序

时间:2015-06-03 19:00:38      阅读:208      评论:0      收藏:0      [点我收藏+]

#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;

}

 

利用动态排序,对学生结构体的各类信息进行排序

原文:http://www.cnblogs.com/GCJ561/p/4549841.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!