C语言运用结构体 指针函数写一个程序 void birth_sort(struct person p[],int n); (7分) 实现公民信息按照生日排序的函数,排序原则:按年龄从大到小排序。其中数组 p 存放 n 个公民信息。
时间: 2024-03-04 20:48:03 浏览: 26
好的,以下是我为您编写的程序:
```c
#include <stdio.h>
#include <stdlib.h>
struct date {
int year;
int month;
int day;
};
struct person {
char name[20];
struct date birth;
};
void birth_sort(struct person p[], int n);
int main() {
int n;
printf("请输入公民数量:");
scanf("%d", &n);
struct person *p = (struct person*) malloc(n * sizeof(struct person));
for(int i = 0; i < n; i++) {
printf("请输入公民姓名:");
scanf("%s", p[i].name);
printf("请输入公民生日(年 月 日):");
scanf("%d%d%d", &p[i].birth.year, &p[i].birth.month, &p[i].birth.day);
}
birth_sort(p, n);
printf("排序结果:\n");
for(int i = 0; i < n; i++) {
printf("%s %d年%d月%d日\n", p[i].name, p[i].birth.year, p[i].birth.month, p[i].birth.day);
}
free(p);
return 0;
}
void birth_sort(struct person p[], int n) {
struct person temp;
for(int i = 0; i < n - 1; i++) {
for(int j = 0; j < n - i - 1; j++) {
if(p[j].birth.year < p[j+1].birth.year || (p[j].birth.year == p[j+1].birth.year && p[j].birth.month < p[j+1].birth.month) || (p[j].birth.year == p[j+1].birth.year && p[j].birth.month == p[j+1].birth.month && p[j].birth.day < p[j+1].birth.day)) {
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
}
```
这个程序首先要求输入公民数量 `n`,然后动态分配内存创建一个 `person` 结构体数组 `p`,并依次输入每个公民的姓名和生日。接下来调用 `birth_sort` 函数实现排序,最后输出排序结果。函数 `birth_sort` 中使用了冒泡排序的思想,按照年、月、日的顺序比较每两个公民的生日,进行交换。