冒泡排序
版本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)