全班 N 个学生,每个学生有学号、姓名、年龄,需要按照年龄进行排序.
#include <stdio.h>
#include <math.h>
#include <string.h>
#define N 5
typedef struct student {
char num[10];
char name[20];
int age;
}stud;
void swap_student(struct student *a, struct student *b) {
stud tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void sort_soap(struct student list[], int len)
{
int i, j;
for (j = 0; j < len-1; j++) {
for (i = 0; i < len-j-1; i++) {
if (list[i].age > list[i+1].age) {
//交换相邻的两个数
swap_student(&list[i], &list[i + 1]);
}
}
}
}
void main(void)
{
//初始化数据
int i;
stud list[N]={
{"2017001","张三",22},
{"2017002","李四",21},
{"2017003","王五",18},
{"2017004","赵六",19},
{"2017005","丁一",20},
};
//排序
sort_soap(list, N);
//打印
for(i = 0; i < N; ++i) {
printf("%s %s %d\n",list[i].num,
list[i].name, list[i].age);
}
}