用C语言写一段代码,实现“对某个专业的学生,按某门课程成绩由低到高进行直接插入排序“这一功能””
时间: 2024-04-07 21:30:02 浏览: 23
当然!以下是用C语言实现按某门课程成绩由低到高进行直接插入排序的代码:
```c
#include <stdio.h>
struct Student {
int id;
char name[50];
float score;
};
void insertionSort(struct Student arr[], int n) {
int i, j;
struct Student key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j].score > key.score) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n, i;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[n];
for (i = 0; i < n; i++) {
printf("Enter details of student %d:\n", i + 1);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Name: ");
scanf("%s", students[i].name);
printf("Score: ");
scanf("%f", &students[i].score);
}
insertionSort(students, n);
printf("\nStudents sorted by score:\n");
for (i = 0; i < n; i++) {
printf("ID: %d, Name: %s, Score: %.2f\n", students[i].id, students[i].name, students[i].score);
}
return 0;
}
```
这段代码通过结构体 `Student` 存储学生的信息,包括学号、姓名和成绩。使用直接插入排序算法按成绩由低到高对学生进行排序。你可以根据需要修改结构体中的字段,以及调整排序的依据。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)