《Python数据结构与算法分析》(第二版)
# !/user/bin/env python
# coding:utf-8
# 冒泡排序,不论列表是否已有序,都进行len(alist)-1趟排序
def bubbleSort(alist):
count = 0# 记录第几趟排序之后列表有序
for passnum in range(len(alist)-1, 0, -1):# range([start, ], stop, [, step])start默认为0,step默认为1
exchanges = False
for i in range(passnum):
if alist[i] > alist[i+1]:
exchanges = True
temp = alist[i+1]
alist[i+1] = alist[i]
alist[i] = temp
if exchanges:
count = count + 1
return count
'''
# 改进排序算法,当上一趟排序没有发生交换时,说明列表已有序,可以终止排序
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
temp = alist[i+1]
alist[i+1] = alist[i]
alist[i] = temp
passnum = passnum - 1
return len(alist)-1-(passnum+1)# 返回第几趟排序之后列表有序
'''
alist = [5, 1, 2, 3, 4, 6, 8]
print(alist)
print(bubbleSort(alist))
# print(shortBubbleSort(alist))
print(alist)