# 选最大的往后排,可排序的列表在前面
def bubbleMaxSort(aList):
for i in range(len(aList)):
for j in range(len(aList) - i - 1):
if aList[j] > aList[j + 1]:
aList[j], aList[j + 1] = aList[j + 1], aList[j]
# 选最小的往前排,可排序的列表在后面
def bubbleMinSort(aList):
for i in range(len(aList)):
for j in range(len(aList) - 1, i, -1):
if aList[j-1] > aList[j]:
aList[j], aList[j-1] = aList[j-1], aList[j]
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleMaxSort(alist)
print(alist)
blist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleMinSort(blist)
print(blist)
# 冒泡排序具有识别排序列表和停止的优点
# 从哪一轮没有交换,就停止了。 因为没有交换就说明有序了。
# 短冒泡排序
def shortBubbleSort(aList):
for i in range(len(aList)):
exchange = False
for j in range(len(aList) - i - 1):
if aList[j] > aList[j + 1]:
aList[j], aList[j + 1] = aList[j + 1], aList[j]
exchange = True
if exchange == False:
print('上一轮没有发生交换,数组已经有序,提前停止')
break
clist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
shortBubbleSort(clist)
print(clist)