Python - 冒泡排序

Python - Bubble sort

您好,我查看了其他有关冒泡排序的帖子,但解决方案对我的情况不起作用: 所以算法一直有效,直到我在循环中重复几次。但是我如何在不使用输入的情况下做到这一点呢?这是我的代码,所以你知道我的意思:

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]
'''

您可以利用 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

编辑:不使用 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

希望我有所帮助!

通过这个算法,你可以预先知道对整个数组进行排序需要多少步(最大),因为该算法是收敛的和有界的。在每一次pass中,最高的未放置值被正确放置,所以你需要n-1次pass才能完成排序。

举个例子:

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)

希望对您有所帮助

PS:您打算做的是,在第 n-1 遍之前对列表进行排序时停止,最好使用 "insertion algorithm" 来完成。插入和冒泡排序之间有一个有趣的比较: Insertion sort vs Bubble Sort Algorithms

我对你的代码进行了一些重构:

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 递归冒泡排序

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))