|
发表于 2023-12-26 09:27:05
|
显示全部楼层
好的,以下是使用选择排序算法进行学生分数排序的修改后代码:
- struct student {
- int id;
- char name[20];
- float score;
- };
- void selectionSort(struct student arr[], int n) {
- int i, j, minIndex;
- struct student temp;
-
- for (i = 0; i < n-1; i++) {
- minIndex = i;
-
- for (j = i+1; j < n; j++) {
- if (arr[j].score < arr[minIndex].score) {
- minIndex = j;
- }
- }
-
- // Swap the current student with the student with minimum score
- temp = arr[i];
- arr[i] = arr[minIndex];
- arr[minIndex] = temp;
- }
- }
- int main() {
- struct student stu[4];
-
- // Input student information
- for (int i = 0; i < 4; i++) {
- printf("请输入第 %d 个学生的学号:", i+1);
- scanf("%d", &stu[i].id);
- printf("请输入第 %d 个学生的姓名:", i+1);
- scanf("%s", stu[i].name);
- printf("请输入第 %d 个学生的分数:", i+1);
- scanf("%f", &stu[i].score);
- }
-
- // Sort student scores using selection sort
- selectionSort(stu, 4);
-
- // Print sorted student information
- printf("学生成绩从小到大排序如下:\n");
- for (int i = 0; i < 4; i++) {
- printf("学号:%d,姓名:%s,分数:%.1f\n", stu[i].id, stu[i].name, stu[i].score);
- }
-
- return 0;
- }
复制代码
在这段修改后的代码中,我添加了一个`selectionSort`函数来实现选择排序算法。该函数接受一个学生结构体数组和数组的大小作为参数。在选择排序中,我们从数组中选出最小的元素,并将其与当前位置进行交换。通过多次循环,就可以将数组按照分数从小到大进行排序。
在主函数中,我们创建了一个学生结构体数组,并通过循环输入学生的信息。然后,调用`selectionSort`函数对学生的分数进行排序。最后,依次输出排序后的学生信息。
希望这次的修改满足了你的需求,如果还有其他问题,请随时提问!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|