C语言学生信息管理系统:插入新学生并排序
C语言学生信息管理系统:插入新学生并排序
目标: 编写一个程序,能够将新学生信息插入到已排序的学生信息列表中,并保持列表的升序排列。
数据结构:
typedef struct Student {
int sno; // 学号
char name[10]; // 姓名
char sex; // 性别
int age; // 年龄
} Student;
typedef struct Table {
Student stu[100]; // 学生信息数组
int num; // 当前学生人数
} Table;
程序逻辑:
- 输入学生信息,包括学号、姓名、性别和年龄。
- 将新学生信息插入到已排序的学生信息列表中,并保持升序排列。
- 输出插入后的学生信息,升序排列。
输入样例:
5
001 Tom M 18
002 Jerry F 17
003 Alice F 19
004 Bob M 20
005 Lily F 18
006 Mary F 21
007 Mike M 22
输出样例:
001 Tom M 18
002 Jerry F 17
003 Alice F 19
004 Bob M 20
005 Lily F 18
006 Mary F 21
007 Mike M 22
代码实现:
#include <stdio.h>
#include <string.h>
// ... (数据结构定义)
// 插入学生信息并排序
void insertStudent(Table *table, Student newStudent) {
// 1. 找到插入位置
int i = 0;
while (i < table->num && table->stu[i].sno < newStudent.sno) {
i++;
}
// 2. 插入新学生信息
for (int j = table->num; j > i; j--) {
table->stu[j] = table->stu[j - 1];
}
table->stu[i] = newStudent;
// 3. 更新学生人数
table->num++;
}
int main() {
Table table = {0}; // 初始化学生信息表
int n; // 学生人数
Student student; // 学生信息
// 输入学生信息
scanf('%d', &n);
for (int i = 0; i < n; i++) {
scanf('%d %s %c %d', &student.sno, student.name, &student.sex, &student.age);
table.stu[i] = student;
table.num++;
}
// 插入新学生信息
scanf('%d %s %c %d', &student.sno, student.name, &student.sex, &student.age);
insertStudent(&table, student);
// 输出学生信息
for (int i = 0; i < table.num; i++) {
printf('%03d %s %c %d
', table.stu[i].sno, table.stu[i].name, table.stu[i].sex, table.stu[i].age);
}
return 0;
}
注意:
- 代码中的数据结构和函数定义可以根据实际需求进行调整。
- 以上代码示例仅供参考,实际实现中可能需要根据具体情况进行修改。
原文地址: https://www.cveoy.top/t/topic/ojJJ 著作权归作者所有。请勿转载和采集!