给出n个学生的考试成绩表,每条信息由姓名和分数组成,试设计一个算法: (1) 按分数高低次序,打印出每个学生在考试中获得的名次,分数相同的为同一名次; (2) 按名次列出每个学生的姓名与分数。用c语言代码实现要求用两种排序方式实现
时间: 2024-02-23 15:59:48 浏览: 121
可以使用结构体来表示每个学生的信息,包括姓名和分数两个成员变量。然后使用两种排序方式(冒泡排序和快速排序)来实现要求。
以下是代码示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100
typedef struct {
char name[20];
int score;
int rank;
} Student;
// 冒泡排序
void bubbleSort(Student students[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (students[j].score < students[j+1].score) {
Student tmp = students[j];
students[j] = students[j+1];
students[j+1] = tmp;
}
}
}
}
// 快速排序
void quickSort(Student students[], int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right;
Student pivot = students[left];
while (i < j) {
while (i < j && students[j].score < pivot.score) {
j--;
}
students[i] = students[j];
while (i < j && students[i].score >= pivot.score) {
i++;
}
students[j] = students[i];
}
students[i] = pivot;
quickSort(students, left, i - 1);
quickSort(students, i + 1, right);
}
int main() {
Student students[MAX_STUDENTS];
int n;
printf("请输入学生人数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d个学生的姓名和分数:", i+1);
scanf("%s %d", students[i].name, &students[i].score);
}
// 按分数排序
bubbleSort(students, n);
int rank = 1;
students[0].rank = 1;
printf("按分数高低次序,打印出每个学生在考试中获得的名次:\n");
printf("%s %d %d\n", students[0].name, students[0].score, students[0].rank);
for (int i = 1; i < n; i++) {
if (students[i].score == students[i-1].score) {
students[i].rank = rank;
} else {
students[i].rank = ++rank;
}
printf("%s %d %d\n", students[i].name, students[i].score, students[i].rank);
}
// 按名次排序
quickSort(students, 0, n-1);
printf("按名次列出每个学生的姓名与分数:\n");
for (int i = 0; i < n; i++) {
printf("%d %s %d\n", students[i].rank, students[i].name, students[i].score);
}
return 0;
}
```
注意,代码中使用的是冒泡排序和快速排序,可以根据实际情况选择其他排序算法。
阅读全文