给出n个学生的考试成绩表,每条信息由姓名和分数组成,试设计一个算法: (1) 按分数高低次序,打印出每个学生在考试中获得的名次,分数相同的为同一名次; (2) 按名次列出每个学生的姓名与分数。用c语言代码实现
时间: 2024-02-23 07:59:30 浏览: 78
以下是基于冒泡排序的实现代码,时间复杂度为O(n^2):
```c
#include <stdio.h>
#include <string.h>
typedef struct {
char name[20];
int score;
int rank;
} Student;
void sort_by_score(Student students[], int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (students[j].score < students[j+1].score) {
Student temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
}
void print_rank_by_score(Student students[], int n) {
int rank = 1;
int i;
students[0].rank = 1;
for (i = 1; i < n; i++) {
if (students[i].score == students[i-1].score) {
students[i].rank = students[i-1].rank;
} else {
students[i].rank = i + 1;
rank = i + 1;
}
}
for (i = 0; i < n; i++) {
printf("%s的名次是%d\n", students[i].name, students[i].rank);
}
}
void print_score_by_rank(Student students[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("第%d名是%s,分数是%d\n", students[i].rank, students[i].name, students[i].score);
}
}
int main() {
Student students[] = {
{"张三", 90},
{"李四", 80},
{"王五", 80},
{"赵六", 70},
{"钱七", 60},
};
int n = sizeof(students) / sizeof(Student);
sort_by_score(students, n);
print_rank_by_score(students, n);
print_score_by_rank(students, n);
return 0;
}
```
其中,`sort_by_score`函数按照成绩从高到低排序;`print_rank_by_score`函数打印出每个学生的排名;`print_score_by_rank`函数按照排名从1到n列出每个学生的姓名和分数。
阅读全文