其他分享
首页 > 其他分享> > 冒泡排序

冒泡排序

作者:互联网

版本1:

def bubble_sort(li):
    length = len(li)
    for i in range(length):
        for j in range(length):
            if li[i] > li[j]:
                li[i],li[j] = li[j],li[i]
li = [1,5,3,7,9,4]
print("li=",li)
bubble_sort(li)
print("sorted li=",li)

版本2:

def bubble_sort(li):
    length = len(li)
    for i in range(length-1):
        for j in range(length-i-1):
            if li[j] > li[j+1]:
                li[j],li[j+1] = li[j+1],li[j]
li = [1,5,3,7,9,4]
print("li=",li)
bubble_sort(li)
print("sorted li=",li)

版本3:

def bubble_sort(li):
    length = len(li)
    for i in range(length-1):
        flag = False
        for j in range(length-i-1):
            if li[j] > li[j+1]:
                li[j],li[j+1] = li[j+1],li[j]
                flag = True
        if not flag:
            return
li = [1,5,3,7,9,4]
print("li=",li)
bubble_sort(li)
print("sorted li=",li)

 

标签:sort,range,冒泡排序,li,length,print,bubble
来源: https://www.cnblogs.com/navysummer/p/15360148.html