冒泡排序

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

冒泡排序

 

上一篇:值得把玩的各色CSS气泡!【精通CSS100例】


下一篇:C语言实现冒泡排序