已知某个班有n(1 <= n <= 100)个学生,输入每行为学生姓名(最多20个字符)和其c语言成绩(0~100),请按照成绩从高到低排序后输出。若有相同的,不能改变其顺序。
时间: 2023-07-14 13:11:50 浏览: 112
可以使用结构体来存储每个学生的姓名和成绩,然后使用快速排序对结构体数组进行排序。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
#define MAX_N 100
#define MAX_NAME_LEN 20
typedef struct {
char name[MAX_NAME_LEN + 1];
int score;
} Student;
void swap(Student *a, Student *b) {
Student tmp = *a;
*a = *b;
*b = tmp;
}
int partition(Student arr[], int low, int high) {
Student pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j].score >= pivot.score) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
void quick_sort(Student arr[], int low, int high) {
if (low < high) {
int pivot_index = partition(arr, low, high);
quick_sort(arr, low, pivot_index - 1);
quick_sort(arr, pivot_index + 1, high);
}
}
int main() {
int n;
Student students[MAX_N];
printf("请输入学生数n: ");
scanf("%d", &n);
printf("请输入每个学生的姓名和成绩:\n");
for (int i = 0; i < n; i++) {
scanf("%s%d", students[i].name, &students[i].score);
}
quick_sort(students, 0, n - 1);
printf("按成绩从高到低排序后的学生信息:\n");
for (int i = 0; i < n; i++) {
printf("%-20s%d\n", students[i].name, students[i].score);
}
return 0;
}
```
输入样例:
```
请输入学生数n: 5
请输入每个学生的姓名和成绩:
Tom 90
Jerry 80
Alice 95
Bob 80
Lucy 85
```
输出样例:
```
按成绩从高到低排序后的学生信息:
Alice 95
Tom 90
Lucy 85
Jerry 80
Bob 80
```
阅读全文