Python 2.7 python中排序的意外输出
这是气泡排序的程序。它没有显示正确的输出。我不明白为什么Python 2.7 python中排序的意外输出,python-2.7,Python 2.7,这是气泡排序的程序。它没有显示正确的输出。我不明白为什么 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]:
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]
您的while循环将在单次传递后终止,因为sorted始终设置为true。尝试将该语句放在for循环之前。好的,我发现了您的问题:While循环只执行一次 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