标签:冒泡 最小 ble 需要 bubble 交换 lis pre 记录
#冒泡排序
#基本思想:两两相邻记录的关键字,如果反序则交换,直到没有反序的记录为止
#要点:1.两两注意是相邻的两个元素的意思
# 2.如果有n个元素需要比较n-1次,每一轮减少1次比较
# 3.既然叫冒泡排序,那就是从下往上两两比较,所以看上去就跟泡泡往上冒一样。
def bubblesort(numList):
leng = len(numList)-1
for i in range(leng): #i=0
for j in range(leng-i):#j=0,1,2,3,4,5,6
if numList[leng-j] < numList[leng-j-1]:#leng-j=6,leng-j-1=5
midnum = numList[leng-j]
numList[leng-j] = numList[leng-j-1]
numList[leng-j-1] = midnum
print(numList)
return numList
print(bubblesort([1,2,-1,8,6,7,-2]))
# [-2, 1, 2, -1, 8, 6, 7] 从后往前,把最小的数排到前面,将-2冒泡到最前
# [-2, -1, 1, 2, 6, 8, 7]
# [-2, -1, 1, 2, 6, 7, 8]
# [-2, -1, 1, 2, 6, 7, 8]
# [-2, -1, 1, 2, 6, 7, 8]
# [-2, -1, 1, 2, 6, 7, 8]
标签:冒泡 最小 ble 需要 bubble 交换 lis pre 记录
原文地址:https://www.cnblogs.com/xhw19950606/p/12274373.html