Python 代码实现冒泡排序改进版

def bubble_sort(numberlist):
    '''冒泡排序'''
    n = len(numberlist)
    for j in range(n-1):
        count = 0
        for i in range(0, n-1-j):
            if numberlist[i] > numberlist[i+1]:
                numberlist[i],numberlist[i+1] = numberlist[i+1],numberlist[i]
                count += 1
        if count == 0:#如果本来是有序的,走一遍就可以直接退出
            return numberlist

if __name__ == '__main__':
    li = [2, 9, 3, -5, 0, 100, 60]
    print(li)
    bubble_sort(li)
    print(li)

C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
[2, 9, 3, -5, 0, 100, 60]
[-5, 0, 2, 3, 9, 60, 100]

Process finished with exit code 0

你可能感兴趣的:(python)