一、实验目的:: (1)能够根据问题描述分析,选择合适的逻辑结构和存储结构,培养学生解决实际应用问题的能力; (2)掌握三种常用排序算法; (3)会对不同算法进行综合分析和比较。 二、实验内容: 创建本班的学生名单,并记录本班数据结构课程的成绩,分别使用以下排序方法对此成绩单进行排序: (1)起泡法对成绩分别进行从高到底和从低到高排序。 (2)折半插入法对成绩分别进行从高到底和从低到高排序。 (3)直接选择排序法对成绩分别进行从高到底和从低到高排序。的代码实现
时间: 2024-02-22 11:01:06 浏览: 79
好的,以下是Python实现的代码示例:
```python
# 定义学生类
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return f"{self.name}: {self.score}"
# 定义排序函数
def bubble_sort(students, reverse=False):
n = len(students)
for i in range(n):
for j in range(n-i-1):
if (not reverse and students[j].score > students[j+1].score) or (reverse and students[j].score < students[j+1].score):
students[j], students[j+1] = students[j+1], students[j]
def binary_insertion_sort(students, reverse=False):
n = len(students)
for i in range(1, n):
low, high = 0, i-1
while low <= high:
mid = (low+high) // 2
if (not reverse and students[i].score < students[mid].score) or (reverse and students[i].score > students[mid].score):
high = mid - 1
else:
low = mid + 1
for j in range(i-1, high, -1):
students[j+1] = students[j]
students[high+1] = students[i]
def selection_sort(students, reverse=False):
n = len(students)
for i in range(n-1):
min_index = i
for j in range(i+1, n):
if (not reverse and students[j].score < students[min_index].score) or (reverse and students[j].score > students[min_index].score):
min_index = j
students[i], students[min_index] = students[min_index], students[i]
# 测试代码
if __name__ == '__main__':
# 创建学生名单
students = [Student('张三', 90), Student('李四', 80), Student('王五', 70), Student('赵六', 85), Student('钱七', 95)]
# 起泡法排序
bubble_sort(students)
print('按照成绩从低到高排序:')
for student in students:
print(student)
bubble_sort(students, reverse=True)
print('按照成绩从高到低排序:')
for student in students:
print(student)
# 折半插入法排序
binary_insertion_sort(students)
print('按照成绩从低到高排序:')
for student in students:
print(student)
binary_insertion_sort(students, reverse=True)
print('按照成绩从高到低排序:')
for student in students:
print(student)
# 直接选择排序法排序
selection_sort(students)
print('按照成绩从低到高排序:')
for student in students:
print(student)
selection_sort(students, reverse=True)
print('按照成绩从高到低排序:')
for student in students:
print(student)
```
希望这个示例代码能够帮助您完成实验内容,如果有任何问题,请随时提出。
阅读全文