#include <stdio.h> struct Student { char name [ 16 ]; // name unsigned char Age; // Age unsigned char Score; // score char classes [ 100 ]; // class }; void the swap ( struct Student ST [], int length) {// this place can be written struct student * st; in fact, may be a structure as to an array operates struct Student tmp; int I, J; for (J = 0 ; J <length; J ++ ) { for ( i = 1; i < length - j; i++) { if (st[i].age < st[i - 1].age) { tmp = st[i]; st[i] = st[i - 1]; st[i - 1] = tmp; } } } } int main() { struct student st[5]= { {"周永康",70,59,"C ++ base class " }, { " XuCaiHou " , 60 , 30 , " the JAVA class " }, { " Bo " , 72 , 90 , " the PHP class " }, { " the scheme " , 50 , 32 , " plane design " }, { " gold three fat " , 30 , 78 , " the IOS system " } }; int length = . 5 ; swap(st,length); for (int i = 0; i < length; i++) { printf("姓名%s,年龄 = %d,成绩 = %d,班级 = %s\n",st[i].name,st[i].age ,st[i].score,st[i].classes); } return 0; }
The second method
#include<stdio.h> struct student { char name[16];//name unsigned char age;//年龄 unsigned char score;//成绩 char classes[100];//班级 }; void swap(struct student* a, struct student* b) { struct student tmp; *a = *b; *b = tmp; } int main() { struct student st[5] = { { " Zhou " , 70 , 59 , " C ++ base class " }, { " XuCaiHou " , 60 , 30 , " the JAVA class " }, { " Bo " , 72 , 90 , " the PHP class " } , { " the scheme " , 50 , 32 , " graphic design " }, { " gold three fat " ,30,78,"IOS"} }; int length = 5; struct student tmp = st[0]; st[0] = st[1]; st[1] = tmp; int i, j; for (i = 0; i < length; i++) { for (j = 1; j < length - i; j++) { if (st[j].age < st[j - 1].age) { swap(&st[j], &st[j - 1]); } } } for (int i = 0; i < length; i++) { printf("姓名%s,年龄 = %d,成绩 = %d,班级 = %s\n", st[i].name, st[i].age, st[i].score, st[i].classes); } return 0; }
Both of these methods, the methods used by the entire structure is seen as an element, like a variable of type int that. By comparison, after the then exchanged between the elements. Values may be passed directly between. This type of change is equivalent to the following code. In these two above code, I advocate the second code, the code
The part of the exchange were drawn out, which helps later use, if the performance has been, we can sort by age in the following section, this part of the exchange we can directly call this function swap it.
void (int *a,int *b) { int c ; if(a>b) { c = a; a = b;b =c; } }