【发布时间】:2014-12-15 20:24:57
【问题描述】:
我刚开始学习 python,我决定尝试做一个冒泡排序。我使用了下面的代码,如果要排序的数字是 0 到 9,它就可以正常工作。之后,它不能正确地对它们进行排序。我认为,据我所知,这是因为它是一个“列表”。
我希望用户能够输入数字,但无论数字的长度如何,程序都会对它们进行排序。任何帮助将不胜感激。
def bubble_sort(items):
changes=0
for i in range(len(items)):
for j in range(len(items)-1-i):#-i = optimised??
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j] # Swap
changes=changes+1
print(items)
print("Number of passes =",i)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers=input()
items=numbers.split()
【问题讨论】: