两种冒泡排序、以python为例。
方法1 :
def bubble(list_temp):
list = list_temp
n = list.len()-1
for j in range(0,n-1):
for i in range(0,n-1-j):
if list[i] > list[i+1]:
list[i],list[i+1]=list[i+1],list[i]
方法2
def bubble_2(temp):
list = list_temp
n = list.len()-1
for j in range(n-1,0,-1):
for i in range(0,j):
if list[i] > list[i+1]:
list[i],list[i+1]=list[i+1],list[i]
这就完了 吗 ? 当然不是 如果在中间的某一次排完以后 ,已经是有序的列表了,可以如下优化
关键点:当某一次排序以后没有进行交换则推出排序
def bubble(list_temp):
list = list_temp
n = list.len()-1
for j in range(0,n-1):
count = 0
for i in range(0,n-1-j):
if list[i] > list[i+1]:
list[i],list[i+1]=list[i+1],list[i]
count+=1
if count == o:
break