# python实现冒泡排序及其优化

## python实现冒泡排序及其优化

def BubbleSort(numList):
if not len(numList):
return
for i in range(len(numList)):
for j in range(len(numList)-1):
if numList[i] < numList[j]:
numList[i], numList[j] = numList[j], numList[i]
return numList

def BubbleSort_optimize(numList):
if not len(numList):
return
for i in range(len(numList)):
j = len(numList)-1
while j > i:
if numList[j] < numList[j-1]:
numList[j], numList[j-1] = numList[j-1], numList[j]
j -= 1
return numList

def BubbleSort_optimize_2(numList):
if not len(numList):
return
isSwap = True
for i in range(len(numList)):
isSwap = False
j = len(numList)-1
while j > i:
if numList[j] < numList[j-1]:
numList[j], numList[j-1] = numList[j-1], numList[j]
isSwap = True
j -= 1
if not isSwap:
return numList
return numList

if __name__ == '__main__':
l1 = [6, 3, 2, -4, -100, 0, 68, 1, 66, 100, 51, 0, 489, -4564, 64]
print(l1)
l2 = l1.copy()
l3 = l1.copy()
l1 = BubbleSort(l1)
print(l1)
BubbleSort_optimize(l2)
print(l2)
BubbleSort_optimize_2(l3)
print(l3)