'''
冒泡排序是一种交换排序,它的基本思想是:两两比较相邻记录的关键字,如果反序则交换,知道没有反序的记录为止
'''
# 元素交换
def swap(list,i,j):
temp = list[i]
list[i] = list[j]
list[j] = temp
# 简单的交换排序,其不满足冒泡排序的基本思想
def BobbleSort0(list):
count = 0
for i in range(len(list)-1):
for j in range(i+1,len(list)):
count+=1
if list[i]>list[j]:
swap(list,i,j)
return count
# 普通冒泡排序
def BobbleSort1(list):
count = 0
for i in range(len(list)):
for j in range(len(list)-2,i-1,-1):
count +=1;
if list[j]>list[j+1]:
swap(list,j,j+1)
return count
# 冒泡排序的优化
def BobbleSort(list):
count = 0
for i in range(len(list)):
flag = False
for j in range(len(list)-2,i-1,-1):
count +=1
if list[j]>list[j+1]:
swap(list,j,j+1)
flag = True
if not flag:
break
return count
# 验证
list = [3,4,6,2,1]
l = BobbleSort0(list)
print("l :",l)
print("list : ",list)
list_a = [3,4,6,2,1]
a = BobbleSort(list_a)
print("a :",a)
print("list_a : ",list_a)
list_b = [3,4,6,2,1]
b = BobbleSort1(list_b)
print("b : ",b)
print("list_b : ",list_b)
list1 = [1,2,3,4,7,5,6]
l1 = BobbleSort0(list1)
print("l1 :",l1)
print("list1 : ",list1)
list_c = [1,2,3,4,7,5,6]
c = BobbleSort(list_c)
print("c :",c)
print("list_d : ",list_c)
list_d = [1,2,3,4,7,5,6]
d = BobbleSort1(list_d)
print("d : ",d)
print("list_d : ",list_d)
Python--冒泡排序及其优化
最新推荐文章于 2023-03-16 19:13:57 发布