在c语言中,输入A组学生姓名和身高,输入B组学生姓名和身高,使用二路归并按照学生身高从低到高排序。然后随机插入一名姓名为李四,身高为1.88M的学生,输出最后的排序的完整代码
时间: 2024-10-14 11:17:29 浏览: 62
在C语言中,你可以使用结构体、动态内存分配以及归并排序算法来实现这个功能。这里是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // 需要包含时间库以实现随机数生成
// 定义学生结构体
typedef struct {
char name[50];
float height;
} Student;
void merge(Student *arr, int left, int mid, int right) {
int i = left, j = mid + 1, k = 0;
Student temp[right - left + 1];
while (i <= mid && j <= right) {
if (arr[i].height <= arr[j].height)
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i <= mid)
temp[k++] = arr[i++];
while (j <= right)
temp[k++] = arr[j++];
for (k = 0; k < right - left + 1; k++)
arr[left + k] = temp[k];
}
void insertion_sort(Student *arr, int n) {
for (int i = 1; i < n; i++) {
Student key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j].height > key.height) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
void merge_and_insertion_sort(Student **groups, int group_count, char new_name[], float new_height) {
// 对每个组分别排序
for (int i = 0; i < group_count; i++) {
insertion_sort(groups[i], group_count);
}
// 合并两个已排序组
Student* merged = (Student*)malloc(sizeof(Student)*(group_count*2));
for (int i = 0; i < group_count; i++) {
memcpy(merged + i, groups[i], sizeof(Student)*group_count);
}
// 插入新学生
Student* insert_pos = merged + group_count;
insert_pos->name = new_name;
insert_pos->height = new_height;
// 使用归并排序将新学生插入到正确位置
merge(merged, 0, group_count - 1, group_count);
// 输出排序后的结果
for (int i = 0; i < group_count + 1; i++) {
printf("%s %.2f\n", merged[i].name, merged[i].height);
}
free(merged); // 释放内存
}
int main() {
srand(time(0)); // 初始化随机数种子
int group_size = 5;
Student *group_A = (Student*)malloc(group_size * sizeof(Student));
Student *group_B = (Student*)malloc(group_size * sizeof(Student));
// 输入A组和B组学生的姓名和身高
for (int i = 0; i < group_size; i++) {
printf("Enter A Group student %d details: ", i+1);
scanf("%s%f", group_A[i].name, &group_A[i].height);
printf("Enter B Group student %d details: ", i+1);
scanf("%s%f", group_B[i].name, &group_B[i].height);
}
// 随机插入李四
char new_name[] = "李四";
float new_height = 1.88; // 单位假设是米
merge_and_insertion_sort(&group_A, 1, new_name, new_height);
merge_and_insertion_sort(&group_B, 1, new_name, new_height);
return 0;
}
```
阅读全文