给出n个学生的考试成绩表,每条信息由姓名和成绩组成,请设计一个算法,实现以下功能: 1)按分数从高到低次序,打印出每个学生的姓名与分数; 2)打印出每个学生在考试中获得的名次,分数相同的为同一名次; 例如: 排序结果如下: 1name:bbbscore:98 2name:cccscore:77 2name:aaascore:77 2name:dddscore:77 5name:fffscore:67 6name:hhhscore:56 6name:gggscore:56 8name:eeescore:55 9name:iiiscore:50 10name:jjjscore:45 [要求]: 1)利用冒泡排序算法对学生成绩进行排序; 2) 分别利用快速排序、直接插入排序对学生成绩进行排序;
时间: 2024-02-02 22:05:33 浏览: 166
实验1_数据结构_输入成绩界面_线性表_
5星 · 资源好评率100%
好的,我可以为您提供一份实现这些功能的算法。首先,让我们定义一个学生类,包括姓名和成绩两个属性:
```python
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
```
然后,我们可以定义一个函数,使用冒泡排序算法对学生列表进行排序,并输出每个学生的姓名和成绩,以及每个学生在考试中的名次:
```python
def bubble_sort(students):
n = len(students)
for i in range(n):
for j in range(n-i-1):
if students[j].score < students[j+1].score:
students[j], students[j+1] = students[j+1], students[j]
for i, student in enumerate(students):
rank = i+1
if i > 0 and student.score == students[i-1].score:
rank = students[i-1].rank
student.rank = rank
print(f"{rank}\tname:{student.name}\tscore:{student.score}")
```
接下来,我们可以定义一个函数,使用快速排序算法对学生列表进行排序,并输出每个学生的姓名和成绩,以及每个学生在考试中的名次:
```python
def quick_sort(students):
if len(students) <= 1:
return students
pivot = students[0].score
left = [student for student in students if student.score > pivot]
middle = [student for student in students if student.score == pivot]
right = [student for student in students if student.score < pivot]
return quick_sort(left) + middle + quick_sort(right)
students = quick_sort(students)
for i, student in enumerate(students):
rank = i+1
if i > 0 and student.score == students[i-1].score:
rank = students[i-1].rank
student.rank = rank
print(f"{rank}\tname:{student.name}\tscore:{student.score}")
```
最后,我们可以定义一个函数,使用直接插入排序算法对学生列表进行排序,并输出每个学生的姓名和成绩,以及每个学生在考试中的名次:
```python
def insert_sort(students):
for i in range(1, len(students)):
j = i
while j > 0 and students[j].score > students[j-1].score:
students[j], students[j-1] = students[j-1], students[j]
j -= 1
for i, student in enumerate(students):
rank = i+1
if i > 0 and student.score == students[i-1].score:
rank = students[i-1].rank
student.rank = rank
print(f"{rank}\tname:{student.name}\tscore:{student.score}")
```
最终,我们可以定义一个主函数,读取从文件中读取学生列表,分别使用冒泡排序、快速排序和直接插入排序算法对学生列表进行排序,并输出排序结果:
```python
def main():
students = []
with open("students.txt", "r") as f:
for line in f:
name, score = line.strip().split()
students.append(Student(name, int(score)))
print("bubble sort:")
bubble_sort(students)
print("quick sort:")
quick_sort(students)
for i, student in enumerate(students):
rank = i+1
if i > 0 and student.score == students[i-1].score:
rank = students[i-1].rank
student.rank = rank
print("insert sort:")
insert_sort(students)
if __name__ == "__main__":
main()
```
希望这份代码可以帮助您实现您的需求。
阅读全文