冒泡算法python动态演示

冒泡算法python动态演示

冒泡算法

文章目录

  • 冒泡算法python动态演示
    • 冒泡算法
    • 冒泡算法python实现
    • 算法动态演示
    • 演示图片保存

冒泡算法(后冒法):
1、每次只确定一个元素;

2、且只有相邻的元素进行交换;

3、两个相邻元素比较,如果该元素比它后面相邻的元素小,则交换两元素位置,一轮结束,确定一个元素位置已排好序列的最前面;

4、下轮从未排好序的元素开始下一轮排序,直到所有元素都排好。

优化:
1、如果不再发生交换时则停止循环;

2、在每轮结束后记录最后一次交换的下标以便于减少遍历次数;

3、每次进行冒泡算法时最好将原列表进行复制,在复制列表进行操作防止改变原表。

冒泡算法python实现

def bubble_sotr(our_list):
    our_sorted_list = our_list[:]  # 防止改变原列表
    last_index = len(our_sorted_list) - 1#改进可以每次记录最后交换的位置,不再交换的元素不需要进行排序
    for i in range(len(our_sorted_list)):  
        flag = True
        for j in range(last_index):
            if our_sorted_list[j] > our_sorted_list[j + 1]:
                flag = False
                our_sorted_list[j], our_sorted_list[j + 1] = our_sorted_list[j + 1], our_sorted_list[j]
                last_index = j
        if flag:
            break
    return our_sorted_list

#测试
our_list = [57, 98, 4, 3, 1, 5, 23, 4, 5, 6, 78, 79]
our_sorted_list = bubble_sotr(our_list)
print(our_list)#[57, 98, 4, 3, 1, 5, 23, 4, 5, 6, 78, 79]
print(our_sorted_list)#[1, 3, 4, 4, 5, 5, 6, 23, 57, 78, 79, 98]


算法动态演示

import matplotlib.pyplot as plt
def draw_bubble_sort(our_list):
    PAUSE_TIME = 4 / len(our_list)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.axis()
    plt.ion()
    our_sorted_list = our_list[:]  # 防止改变原列表
    last_index = len(our_sorted_list) - 1
    for i in range(len(our_sorted_list)):
        flag = True
        for j in range(last_index):
            if our_sorted_list[j] > our_sorted_list[j + 1]:
                flag = False
                our_sorted_list[j], our_sorted_list[j + 1] = our_sorted_list[j + 1], our_sorted_list[j]
                last_index = j
            plt.cla()#清除画布
            ax.bar(range(len(our_sorted_list)), our_sorted_list, align='center')
            for a, b in zip(range(len(our_sorted_list)), our_sorted_list):
                ax.text(a, b + 0.05, b, ha='center')
            ax.bar(j, our_sorted_list[j], color='r', align='center')
            ax.bar(j + 1, our_sorted_list[j + 1], color='y', align='center')
            plt.pause(PAUSE_TIME)
        if flag:
            break
    return our_sorted_list

实验结果:

在这里插入图片描述

演示图片保存

虽然我们画出了动态演示图,但是图片的保存比较麻烦。这里我们使用 FuncAnimation() 来保存。

首先我们需要一个动态更新函数,这里我们建立一个更新类。

class Undate:
    def __init__(self, our_list, change_indexs):#初始化
        self.our_list = our_list#注意这里的列表不再是我们需要排序的列表,而是排序过程中所有出现的列表可能性的集合
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(1, 1, 1)
        self.ax.axis()
        self.count = 0 #用于计数,读取变化的列表
        self.change_indexs = change_indexs

    def update(self, j):#更新函数
        self.ax.cla()
        self.ax.bar(range(len(self.our_list[self.count])), self.our_list[self.count], align='center')
        for a, b in zip(range(len(self.our_list[self.count])), self.our_list[self.count]):
            self.ax.text(a, b + 0.05, b, ha='center')
        self.ax.bar(j, self.our_list[self.count][j], color='r', align='center')
        self.ax.bar(j + 1, self.our_list[self.count][j + 1], color='y', align='center')
        self.count += 1

    def iter_fun(self):	#迭代函数,生成器,用于读取排序过程中变化的序列号
        for i in self.change_indexs:
            yield i

原来的排序函数需要重新写:

def draw_bubble_sotr(our_list):
    PAUSE_TIME = 4 / len(our_list)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.axis('equal')
    plt.ion()

    our_sorted_list = our_list[:]  # 防止改变原列表
    last_index = len(our_sorted_list) - 1
    change_indexs = [] #计录变化的列表序列
    change_list = []   #存储变化的序列
    for i in range(len(our_sorted_list)): 
        flag = True
        for j in range(last_index):
            if our_sorted_list[j] > our_sorted_list[j + 1]:
                flag = False
                our_sorted_list[j], our_sorted_list[j + 1] = our_sorted_list[j + 1], our_sorted_list[j]
                last_index = j
            change_indexs.append(j) #加入列表序列号
            temp = our_sorted_list[:]
            change_list.append(temp)	#加入列表序列
        if flag:
            break

    return our_sorted_list, change_indexs, change_list

保存动态图:

our_list = [57, 98, 4, 3, 1, 5, 23, 4, 5, 6, 78, 79]
our_sorted_list, change_indexs, change_list = draw_bubble_sotr(our_list)
#创建更新类
up = Undate(change_list, change_indexs)
#调用FuncAnimation()函数,参数fig为画布,参数func为需要传入的更新函数、参数frames为需要传给#func函数的参数,参数interval设置绘制速率。
ani = FuncAnimation(fig=up.fig, func=up.update, frames=up.iter_fun(), interval=400)
ani.save('bubble_sort.gif')#保存图片
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值