[英]Python bubble sort - Sorting an element more than once
The objective of this is to take a list of positive integers and sort them using bubble sort. 目的是获取一个正整数列表,并使用冒泡排序对其进行排序。 It works whenever you input a list that does not require a single element to be moved more than once.
只要您输入不需要将单个元素多次移动的列表,它就会起作用。 How do I get it to move an element more than once?
如何使元素移动一次以上?
For example, inputting [3,5,4,6,7] works but [10,9,8,7,6] does not. 例如,输入[3,5,4,6,7]有效,但是[10,9,8,7,6]无效。
def bubbleSort(lis):
swapped = True
while swapped:
swapped = False
for i in range(0,len(lis)-1):
if lis[i] > lis[i + 1] or lis[i] == lis[i+1]:
switch = lis[i]
lis[i] = lis[i+1]
lis[i+1] = switch
return lis
print(lis)
print(bubbleSort([3,5,4,6,7]))
print(bubbleSort([10,9,8,7,6]))
The problem is that you return after only one pass through the list. 问题是您仅在通过列表之后返回。 Wait until
swapped
is False
. 等到
swapped
为False
。
Also, you must set swapped
when you make a switch. 另外,进行
swapped
时必须设置swapped
。
swapped = True
while swapped:
swapped = False
for i in range(0,len(lis)-1):
if lis[i] > lis[i + 1] or lis[i] == lis[i+1]:
swapped = True
switch = lis[i]
lis[i] = lis[i+1]
lis[i+1] = switch
return lis
I removed the print
statement because you can never reach it, and that should be the job of the calling program. 我删除了
print
语句,因为您永远无法到达它,这应该是调用程序的工作。
You should not set swapped to 'false' when you enter the while loop, because then you make only one iteration of the loop. 进入while循环时,不应将swapd设置为“ false”,因为这样一来,循环仅进行一次迭代。 You should exit the loop when there are no more swaps when you iterate over the entire list.
当遍历整个列表时没有更多交换时,应退出循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.