这是冒泡排序的程序。它没有显示正确的输出。我不明白为什么。
numbers = input("enter nos.: ")
my_list = list(numbers)
def bubble(list):
length = len(list) - 1
sorted = False
while sorted == False:
for i in range(length):
if list[i] > list[i+1]:
sorted = False
list[i], list[i+1] = list[i+1], list[i]
sorted = True
bubble(my_list)
print "Sorted list is: ",my_list
输出:
enter nos.: 1,454,867,43,421,0,8,43,121,45656,76,4,34,1
Sorted list is: [1, 454, 43, 421, 0, 8, 43, 121, 867, 76, 4, 34, 1, 45656]
答案 0 :(得分:0)
你的while循环将在单次传递后终止,因为sorted总是设置为true。尝试将该语句放在for循环之前。
答案 1 :(得分:0)
好吧我找到了你的问题:While循环只执行一次。
您的状态为sorted == False
,如果进行反转,则设置sorted = False
。你必须改变它:
numbers = input("enter nos.: ")
my_list = list(numbers)
def bubble(list):
length = len(list) - 1
sorted = True
while sorted == True:
sorted = False
for i in range(length):
if list[i] > list[i+1]:
list[i], list[i+1] = list[i+1], list[i]
sorted = True
bubble(my_list)
print "Sorted list is: ",my_list