python选择排序并绘图展示

选择排序

选择排序
输出结果:

选择排序:
[3, 2, 9, 7, 1, 6]
[3, 2, 9, 7, 1, 6]
[1, 2, 9, 7, 3, 6]
[1, 2, 9, 7, 3, 6]
[1, 2, 9, 7, 3, 6]
[1, 2, 3, 7, 9, 6]
[1, 2, 3, 7, 9, 6]
[1, 2, 3, 6, 9, 7]
[1, 2, 3, 6, 9, 7]
[1, 2, 3, 6, 7, 9]

程序

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

def selection_sort(a):
    print('选择排序:')
    plt.figure()
    plt.style.use('ggplot')
    plt.ion()   #开启交互模式
    draw(a)
    for i in range(len(a)-1):
        min_index=i
        for j in range(i+1,len(a)):
            if a[j]<a[min_index]:
                min_index=j
                print(a)
                draw(a,i,min_index)
        if i!=min_index:
            a[i],a[min_index]=a[min_index],a[i]
            print(a)
            draw(a,i,min_index)
    draw(a)
    plt.ioff()  #关闭交互模式
    plt.show()
    
def draw(a,i=None,min_index=None):
    plt.cla()   #清屏
    x=plt.bar(range(1,len(a)+1),a,width=0.5,color='steelblue')
    if i!=None:
        x[i].set_color('indianred')
    if min_index!=None:
        x[min_index].set_color('indianred')
    for m,n in zip(range(1,len(a)+1),a):
        plt.text(m,n,n,ha='center',va='bottom',fontsize=14,color='black')   #柱状图上方显示数值
    plt.xticks(())  #不显示x轴
    plt.yticks(())  #不显示y轴
    plt.title('选择排序')
    plt.pause(2)    #每次图形变动都停两秒

if __name__=='__main__':
    a=[3,2,9,7,1,6]
    selection_sort(a)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值