python 冒泡排序
冒泡排序:
相邻的两个数字先进行比较,也就是li[0]和li[1]进行比较,如果不是大于的关系,就继续依次进行li[1]和li[2]比较,进行交换然后每一次扫描得到的新列表如下:
li = [11,22,32,344,3,] for i in range(len(li)-1): xin = (li[i]) kai = li[i+1] if li[i] >li[i+1]: temp = li[i] li[i] = li[i+1] li[i+1]=temp print(li) for i in range(len(li)-2): xin = (li[i]) kai = li[i+1] if li[i] >li[i+1]: temp = li[i] li[i] = li[i+1] li[i+1]=temp print(li) for i in range(len(li)-3): xin = (li[i]) kai = li[i+1] if li[i] >li[i+1]: temp = li[i] li[i] = li[i+1] li[i+1]=temp print(li) for i in range(len(li)-3): xin = (li[i]) kai = li[i+1] if li[i] >li[i+1]: temp = li[i] li[i] = li[i+1] li[i+1]=temp print(li) 执行结果: [11, 22, 32, 3, 344] [11, 22, 3, 32, 344] [11, 3, 22, 32, 344] [3, 11, 22, 32, 344] 冒泡排序 for j in range(len(li)): #j:1,2,3 for i in range(len(li)-1): if li[i] >li[i+1]: temp = li[i] li[i] = li[i+1] li[i+1]=temp print(li) 执行结果 [3, 11, 22, 32, 344]