冒泡排序
冒泡排序
原理
冒泡排序多次遍历列表。他比较相邻的元素,将不合顺序的交换。每一轮遍历都将下一个最大值放大正确的位置上。本质上,每个元素通过“冒泡”找打自己所属的位置。
代码实现
#!usr/bin/env python
#-*- coding:utf-8 _*-
# __author__:lianhaifeng
# __time__:2020/8/12 23:41
def bubbleSort(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
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
passnum -= 1
def bubbleSort2(alist):
passnum = len(alist) - 1
for i in range(passnum, -1, -1):
for j in range(i):
if alist[j] > alist[j+1]:
alist[j], alist[j+1] = alist[j+1], alist[j]
if __name__ == '__main__':
alist = [8, 38, 65, 97, 76, 13, 27, 49]
bubbleSort(alist)
print(alist)
alist = [8, 38, 65, 97, 76, 13, 27, 49]
bubbleSort2(alist)
print(alist)