优化思路:当某一次循环结束后列表无变化就说明排序已完成,可以终止运算
实现方法:设定一个控制变量初值为True,当发生元素交换时控制变量值变为False,每次循环结束后判断控制变量,为True时退出
def BubbleSort3(a):
for i in range(len(a)-1):
flag = True
for j in range(len(a)-1-i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
flag = False
if not flag:
flag = True
for j in reversed(range(i+1,len(a))):
if a[j] < a[j-1]:
a[j], a[j-1] = a[j-1], a[j]
flag = False
if flag:
break
return a
测试
import numpy as np
L = np.random.randn(10)
L
array([-1.10054952, -0.4185791 , -0.07602447, 0.79757332, 1.49879348,
-1.62739817, 0.96014521, -0.64522841, -0.80705511, -1.41251621])
BubbleSort(L)
array([-1.62739817, -1.41251621, -1.10054952, -0.80705511, -0.64522841,
-0.4185791 , -0.07602447, 0.79757332, 0.96014521, 1.49879348])