冒泡排序:
- 冒泡排序,每次都是从左往右,交换相邻的元素,从而达到循环一边可以把最大的元素放在右边。
- 时间复杂度:平均:O(n²),最好:O(n),最坏:O(n2),稳定性:稳定。
上代码
def bubble(lists, map=lambda x, y: x>y):
# 未优化
# 冒泡排序。
# listlen = len(lists)
for x in range(len(lists)-1):
istrue = False
for i in range(len(lists)-1):
if map(lists[i], lists[i+1]):
istrue=True
lists[i], lists[i+1] = lists[i+1], lists[i]
if not istrue:
break
return lists
lists = [54, 26, 93, 77,17, 77, 31, 44, 55, 20]
print(bubbling(lists))
双向冒泡排序
从名字就可以看出来,是双向的冒泡排序。
冒泡排序,每次都是从左往右,交换相邻的元素,从而达到循环一边可以把最大的元素放在右边。
而双向冒泡排序,在完成一次从左往右的冒泡排序后,再从右往左进行冒泡,从而把小的元素放在左边。
上图
上码
def bubbling(lists, map=lambda x, y: x>y):
# 双向冒泡排序。
for x in range(len(lists)-1):
istrue = False
for i in range(len(lists)-1):
if map(lists[i], lists[i+1]):
lists[i], lists[i+1] = lists[i+1], lists[i]
istrue = True
if istrue == True:
for i in range(len(lists)-2, x, -1):
if map(lists[i-1], lists[i]):
lists[i-1], lists[i] = lists[i], lists[i-1]
istrue = True
if not istrue:
break
return lists
lists = [8, 7, 6, 5, 4, 3, 2, 1]
print(bubbling(lists))