双向冒泡:①从左往右,交换相邻的元素,从而达到循环一边可以把最大的元素放在右边;②从右往左进行冒泡,从而把小的元素放在左边。循环直至排序结束。
用代码块功能插入代码,请勿粘贴截图
def bubbleSort(alist):
for passnum in range(len(alist)-1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist)
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist)-1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i]>alist[i+1]:
exchanges = True
alist[i], alist[i + 1] = alist[i + 1], alist[i]
passnum = passnum-1
alist = [20, 30, 40, 90, 50, 60, 70, 80, 100, 110]
shortBubbleSort(alist)
print(alist)
我的解答思路和尝试过的方法
我想要达到的结果双向冒泡:①从左往右,交换相邻的元素,从而达到循环一边可以把最大的元素放在右边;②从右往左进行冒泡,从而把小的元素放在左边。循环直至排序结束。