修复冒泡排序算法中的一个错误
已为您提供一个使用 bubble sort 算法对数字列表进行排序的程序。在测试时,您发现代码不正确。请修正该算法,使其能正确运行。
本练习是课程的一部分
Python 中的数据结构与算法
练习说明
- 修正
is_sorted变量赋值中的错误。 - 修正检查相邻值时的错误。
- 修正更新
list_length变量时的错误。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def bubble_sort(my_list):
list_length = len(my_list)
# Correct the mistake
is_sorted = True
while not is_sorted:
is_sorted = True
for i in range(list_length-1):
# Correct the mistake
if my_list[i] < my_list[i+1]:
my_list[i] , my_list[i+1] = my_list[i+1] , my_list[i]
is_sorted = False
# Correct the mistake
list_length += 1
return my_list
print(bubble_sort([5, 7, 9, 1, 4, 2]))