优化冒泡排序(python)
'''
记录交换操作发生的位置,如果没有发生交换操作,则代表排序已经可以终止
这样一来冒泡排序最好的情况下,时间复杂度就从O(n^2)优化到了O(n)
'''
def imroved_bubble_sort(l):
length = len(l)
swaplast = length - 1
for i in range(len(l)):
sign = swaplast
for j in range(swaplast):
if l[j] > l[j+1]:
temp = l[j+1]
l[j + 1] = l[j]
l[j] = temp
swaplast = j
if sign == swaplast:
break