卡在python中进行冒泡排序(仅使用while循环)

时间:2018-08-09 08:58:26

标签: python python-3.x python-requests

def bubble_sort(alist):
    i = 0
    j = 0
    while i<len(alist):
        while j<(len(alist)-1-i):
            if alist[j]>alist[j+1]:
                temp = alist[j]
                alist[j] = alist[j+1]
                alist[j+1] = temp
            j = j+1

        i = i + 1
    return alist 

abc = [54,26,93,17,77,31,44,55,20]
alist1 = bubble_sort(abc)
print(alist1)

我不知道为什么只经过一遍。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您只需要在第一个while循环内移动初始化j=0,如下所示。请注意,您也可以像我一样以较短的方式在Python中交换两个值:

def bubble_sort(a):
    i = 0
    while i<len(a):
        j = 0
        while j<(len(a)-1-i):
            if a[j]>a[j+1]:
                a[j], a[j+1] = a[j+1], a[j]
            j = j+1  
        i = i + 1
    return a 

abc = [54,26,93,17,77,31,44,55,20]
alist1 = bubble_sort(abc)
print(alist1)   # [17, 20, 26, 31, 44, 54, 55, 77, 93]