首页 > 代码库 > 新手笔记-简单的排序练习
新手笔记-简单的排序练习
根据分数排序和名字字母排序
2 #include <string.h> 3 #include <stdio.h> 4 struct person{ 5 char *name; 6 int score; 7 }; 8 9 int init(struct person *p, char *name, int score)10 {11 p->name = name;12 p->score = score;13 }14 15 int find_max(struct person *p)16 {17 int i, j;18 int max = p->score;19 for(i=0; i<6; i++)20 {21 if((p+i)->score > max)22 max = (p+i)->score;23 }24 25 return max;26 }27 28 int sort(struct person *p)29 {30 int i=0, j=0, max=0, maxi=0, k=0;31 char *arr;32 for(i=0; i<6; i++)33 {34 maxi=i;35 max = (p+i)->score;36 for(j=i+1; j<6; j++)37 {38 if((p+j)->score > max)39 {40 max = (p+j)->score;41 maxi = j;42 }43 }44 arr = (p+i)->name;45 (p+i)->name = (p+maxi)->name;46 (p+maxi)->name = arr;47 48 k = (p+i)->score;49 (p+i)->score = (p+maxi)->score;50 (p+maxi)->score = k;51 52 printf("sss is %d \n", (p+i)->score);53 }54 55 }56 57 int sort1(struct person *p)58 {59 int i, j, k, m;60 char *arr;61 62 for(i=0; i<6; i++)63 {64 for(j=i+1; j<6; j++)65 {66 m = strcmp((p+i)->name , (p+j)->name);67 if(m > 0)68 {69 arr = (p+i)->name;70 (p+i)->name = (p+j)->name;71 (p+j)->name = arr;72 73 k = (p+i)->score;74 (p+i)->score = (p+j)->score;75 (p+j)->score = k;76 }77 }
结果:
sss is 98 sss is 88 sss is 79 sss is 67 sss is 65 sss is 60 tom , 98jams , 88jim , 79lucy , 67tubi , 65suoluo , 60jams , 88jim , 79lucy , 67suoluo , 60tom , 98tubi , 65avg is 76max is 98
这里分数用的是选择排序,字母用的是冒泡排序
注意:使用选择排序时 maxi 要赋值为当前 i ,每次要从下一次开始,对算法要多思考多练习。
新手笔记-简单的排序练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。