1 #冒泡排序,对列表进行升序排序
2 def bubble_sort(alist):
3 #相邻两个元素进行比较,如果发现位置错误就进行交换
4 n = len(alist)
5 for k in range(n-1):
6 for i in range(n-1-k):
7 if alist[i] > alist[i+1]:
8 alist[i],alist[i+1] = alist[i+1],alist[i]
9 #如果传入的列表是有序的,只需要检测一轮,查看是否发生交换,没有发生交换,则退出循环。
10 def bubble_sort2(alist):
11 #相邻两个元素进行比较,如果发现位置错误就进行交换
12 n = len(alist)
13 for k in range(n-1):
14 count = 0
15 for i in range(n-1-k):
16 if alist[i] > alist[i+1]:
17 alist[i],alist[i+1] = alist[i+1],alist[i]
18 count += 1
19 #判断count的值是否等于0,等于0则说明没有发生交换
20 if count == 0:
21 break
22 alist = [4,7,32,6,9,10,34,24,7,8,67,40,78,88]
23 print('原数组:',alist)
24 bubble_sort(alist)
25 print('现数组:',alist)
26 alist2 = [2,3,4,5,6,7,8,9,10,11]
27 bubble_sort2(alist2)
28 print('有序列表:',alist2)
29
原数组: [4, 7, 32, 6, 9, 10, 34, 24, 7, 8, 67, 40, 78, 88]
现数组: [4, 6, 7, 7, 8, 9, 10, 24, 32, 34, 40, 67, 78, 88]
有序列表: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]