# 方法1 a = [1,7,4,89,34,2] for i in range(1,len(a)): # a[0],a[1],a[2]... 取不了len(a) for j in range(i+1): # a[0],a[1],a[i+1] if a[j]>a[i] : a[j],a[i] = a[i],a[j] print(a) # 方法2 相邻两元素比较 def bubbleSort1(a1): for i in range(1,len(a1)-1): # 跑n-1趟,循环负责设置冒泡排序进行的次数 for j in range(len(a1)-i): # j为列表下标,到i-1为止 if a1[j]>a1[j+1]: a1[j],a1[j+1] = a1[j+1],a1[j] print(a1) bubbleSort1([1,7,4,89,34,2])