[英]Python - Bubble sort
Hi I reviewed other posts with bubble sort, but solution didn't work in my case: So algorithm works until I repeat few times while loop.嗨,我用冒泡排序查看了其他帖子,但解决方案在我的情况下不起作用:所以算法有效,直到我在循环中重复几次。 But how can I do this without using input?
但是如何在不使用输入的情况下做到这一点? Here is my code so you know what I mean:
这是我的代码,所以你知道我的意思:
x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]
h = None
flag = True
while flag == True:
#flag = True
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
# flag = False
h = x[i]
x[i] = x[i + 1]
x[i + 1] = h
print(x)
#input = raw_input('Satisfied? ')
#if input == 'q':
# break
print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''
You can make use of the sorted
function in python, and change your code to be:您可以使用 python 中的
sorted
函数,并将代码更改为:
while flag == True:
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
h = x[i]
x[i] = x[i + 1]
x[i + 1] = h
if sorted(x) == x: #x is already sorted
flag = False
Edit: Alternate solution which doesn't use python's built in sort function:编辑:不使用 python 内置排序函数的替代解决方案:
while flag == True:
flag = False
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
flag = True
h = x[i]
x[i] = x[i + 1]
x[i + 1] = h
Hope I helped!希望我有所帮助!
With this algorithm, you can previously know how many steps (max) are needed to sort the whole array, because the algorithm is convergent and bounded.使用此算法,您可以事先知道对整个数组进行排序需要多少步(最大),因为该算法是收敛且有界的。 In each pass, the highest no-placed value is placed correctly, so you will need n-1 passes to complete the sorting.
在每次传递中,最高的未放置值都被正确放置,因此您将需要 n-1 次传递才能完成排序。
Here an example:这里有一个例子:
mylist = [54,26,93,17,77,31,44,55,20]
for num in range(len(mylist)-1, 0, -1):
for i in range(num):
if mylist[i] > mylist[i+1]:
aux = mylist[i]
mylist[i] = mylist[i+1]
mylist[i+1] = aux
print(mylist)
Hope it helps希望它有帮助
PS: What you intended to do, stopping when the list is sorted before the n-1 pass, is better done with the "insertion algorithm". PS:你打算做的,在n-1遍之前对列表进行排序时停止,最好使用“插入算法”来完成。 Here there is an interesting comparision between insertion and bubble sorting: Insertion sort vs Bubble Sort Algorithms
这里有一个插入排序和冒泡排序之间的有趣比较: 插入排序 vs 冒泡排序算法
I little refactor for your code:我很少重构你的代码:
for num in range(len(mylist)-1, 0, -1):
for i in range(num):
if mylist[i] > mylist[i+1]:
mylist[i], mylist[i+1] = mylist[i+1], mylist[i]
Python recursive bubble sort Python递归冒泡排序
def bubble_f(lst):
if len(lst) < 2:
return lst
if lst[0] > lst[1]:
return [lst[1]] + bubble_f([lst[0]] + lst[2:])
return [lst[0]] + bubble_f([lst[1]] + lst[2:])
def bubble_sort(lst):
if len(lst) < 2:
return lst
sorted = bubble_f(lst)
return bubble_sort(sorted[:-1]) + [sorted[-1]]
list1 = [5, 9, 23, 4, 3, 8, 1, 12, 2, 9, 15, 19, 11, 27, 0]
print(bubble_sort(list1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.