#import <Foundation/Foundation.h>
//定义一个结构体,使用函数回调实现动态排序(年龄.姓名.分数)
typedef struct student{
char name[50];
int age;
float score;
}Student;
BOOL compareName(Student stu1,Student stu2); //声明
BOOL compareName(Student stu1,Student stu2){ //按姓名排序实现
return strcmp(stu1.name,
stu2.name);
}
BOOL compareAge(Student stu1,Student stu2);
//声明
BOOL compareAge(Student stu1,Student stu2){
//按年龄排序实现
return stu1.age>stu2.age?YES:NO;
}
BOOL compareScore(Student stu1,Student stu2);
//声明
BOOL compareScore(Student stu1,Student stu2){
//按分数排序实现
return stu1.score>stu2.score?YES:NO;
}
void bubbleArray(Student *a,int count,BOOL (*p)(Student,Student));
void bubbleArray(Student *a,int count,BOOL (*p)(Student,Student)){
//运行时函数,参数:一个指针变量,一个长度,一个函数指针
for (int i=0;
i<count-1; i++) {
for (int j=0;
j<count-1-i; j++) {
if (p(a[ j ],a[j+1]))
{ //由参数函数指针所指向的函数决定按什么类型排序
Student temp=a [ j ];
a[ j ]=a[j+1];
a[j+1]=temp;
}
}
}
for (int i=0;
i<count; i++) { //遍历
printf("%s
%d %.2f \n",a[ i ].name,a[ i ].age,a[
i ].score);
}
}
int main(int argc, const char *
argv[]) {
Student stuArray[ 5 ]={
//定义一个结构体数组
{"xi*",98,80.0},
{"aobama",75,60.1},
{"benladeng",55,56.3},
{"pujing",58,88.6},
{"chengguan",63,98.0}
};
BOOL (*p)(Student,Student)=NULL;
//函数指针初始化
p=compareAge; //为函数指针赋值,指向的是函数compareAge的地址
// p=compareName;
// p=compareScore;
bubbleArray(stuArray, 5,
p); //调用函数
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。