冒泡排序
冒泡排序是从序列的一端开始往另一端冒泡,依次比较相邻的两个数的大小,使大的向右移动,经过一轮比较,序列中最大的数就象气泡一样冒起来,移动到最右端。
冒泡排序算法的原理如下:
- 比较相邻的元素。如果前一个比后一个大,就交换他们两个。
- 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
- 针对所有的元素重复以上的步骤,除了最后一个。
- 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
原始数据顺序
[5,1,8,6,4,3]
第一轮
第1轮排序
第1次排序结果[1, 5, 8, 6, 4, 3] # 第一次5 和 1 交换
第2次排序结果[1, 5, 8, 6, 4, 3] # 第二次无交换 5 < 8
第3次排序结果[1, 5, 6, 8, 4, 3] # 第三次8 和 6 交换
第4次排序结果[1, 5, 6, 4, 8, 3] # 第四次8 和 4 交换
第5次排序结果[1, 5, 6, 4, 3, 8] # 第五次8 和 3 交换,此时最大数 8 到最右侧
第二轮
第2轮排序
第1次排序结果[1, 5, 6, 4, 3, 8] # 第一次无交换 1 < 5
第2次排序结果[1, 5, 6, 4, 3, 8] # 第二次无交换 5 < 6
第3次排序结果[1, 5, 4, 6, 3, 8] # 第三次4 和 6 交换
第4次排序结果[1, 5, 4, 3, 6, 8] # 第四次6 和 3 交换,此时第二大数 6 到右二位置
第三轮
第3轮排序
第1次排序结果[1, 5, 4, 3, 6, 8] # 第一次无交换 1 < 5
第2次排序结果[1, 4, 5, 3, 6, 8] # 第二次5 和 4 交换
第3次排序结果[1, 4, 3, 5, 6, 8] # 第三次5 和 3 交换,此时第三大数 5 到右三位置
第四轮
第4轮排序
第1次排序结果[1, 4, 3, 5, 6, 8] # 第一次无交换 1 < 4
第2次排序结果[1, 3, 4, 5, 6, 8]# 第一次4 和 3 交换,此时第四大数 4 到右四位置
第五轮无交换
第5轮排序
第1次排序结果[1, 3, 4, 5, 6, 8]# 第一次无交换,此时已经得到升序排序结果
第六轮无交换
def bubble_sort(lists):
# 对列表中的数据进行冒泡排序
count = len(lists)
for i in range(0, count):
print('第{}轮排序'.format(i+1))
for j in range(0, count - i - 1): # count - i 是为减少循环次数,最右i个数是已经排好序的
if lists[j] > lists[j + 1]:
lists[j], lists[j + 1] = lists[j + 1], lists[j]
print('第{}次排序结果{}'.format(j + 1,ls)) # 每完成一轮排序输出一个空行
import random
ls = [random.randint(1,100) for i in range(10)]
bubble_sort(ls)
可以结合matplotlib绘制动态演示
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro',animated=True)
x = np.arange(1,11)
nums = [np.random.randint(0,100) for i in range(10)]
for i in range(len(nums) - 1):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
plt.ion() # 打开交互模式
plt.cla() # 清除内容
plt.bar(x, nums, align='center')
plt.bar(j, nums[j], color="r", align="center")
plt.bar(j + 1, nums[j + 1], color="r", align="center")
plt.pause(0.1) # 暂停
plt.ioff() # 关闭交互模式
plt.show()
用set_xdata/set_ydata更新数据,pause刷新图像可以实现动画功能,但是效率非常低,8组数据+20帧的配置就拽不动了,有明显的滞后,应该是pause导致的。