新手笔记-简单的排序练习

根据分数排序和名字字母排序





 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 , 98
jams , 88
jim , 79
lucy , 67
tubi , 65
suoluo , 60
jams , 88
jim , 79
lucy , 67
suoluo , 60
tom , 98
tubi , 65
avg is 76
max is 98

 这里分数用的是选择排序,字母用的是冒泡排序

注意:使用选择排序时 maxi 要赋值为当前 i ,每次要从下一次开始,对算法要多思考多练习。

posted @ 2014-10-16 19:06  Qt小罗  阅读(237)  评论(0编辑  收藏  举报