冒泡排序(Bubble Sort)是一种很原始的排序方法,就是通过不断地交换“大数”的位置达到排序的目的。
-
原理
冒泡算法的原理就是比较相邻两个数字的大小。将两数中比较大的那个数交换到靠后的位置。不断地交换下去就可以将最大的那个数放到队列的尾部。然后重头再次交换,直到将数列排成有序数列。
-
代码
在写冒泡程序的代码之前,需要创建一个无序数列的程序,用于测试排序算法,创建无序排列的数列程序为randomList.py
import random
def randomList(n):
'''返回一个长度为n的列表,数据范围 [0,100)'''
l = []
for i in range(n):
h = random.randrange(100)
l.append(h)
return l
if __name__ == "__main__":
iList = randomList(10)
print(iList)
结果为:
[91, 72, 61, 36, 89, 44, 89, 30, 71, 31]
冒泡排序的程序bubbleSort的代码如下:
from randomList import randomList
import timeit
ilist = randomList(20)
def bubbleSort(ilist):
'''冒泡排序'''
if len(ilist) <= 1:
return ilist
for i in range(1, len(ilist)):
for j in range(0, len(ilist) - i):
if ilist[j] > ilist[j + 1]:
ilist[j], ilist[j + 1] = ilist[j + 1], ilist[j]
# print(f"第%d轮排序结果:" % i)
# print(ilist)
return ilist
if __name__ == "__main__":
print(ilist)
print(bubbleSort(ilist))
print(timeit.timeit("bubbleSort(ilist)", "from __main__ import bubbleSort,ilist", number=100))
结果为:
[62, 91, 9, 82, 79, 99, 13, 75, 98, 86, 28, 67, 70, 25, 42, 66, 49, 63, 77, 97]
[9, 13, 25, 28, 42, 49, 62, 63, 66, 67, 70, 75, 77, 79, 82, 86, 91, 97, 98, 99]
0.0017067000000000054
bubbleSort.py的第九行导入了之前的randomList函数,用于创建了一个无序的数列,还导入了timeit模块,用于测试函数的运行时间。
最后显示结果:
第一行为排序前,第二行为排序后,第三行为运行时间