插入排序
输出结果:
插入排序:
[2, 3, 9, 7, 1, 6]
[2, 3, 7, 9, 1, 6]
[2, 3, 7, 1, 9, 6]
[2, 3, 1, 7, 9, 6]
[2, 1, 3, 7, 9, 6]
[1, 2, 3, 7, 9, 6]
[1, 2, 3, 7, 6, 9]
[1, 2, 3, 6, 7, 9]
程序
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
def insertion_sort(a):
print('插入排序:')
plt.figure()
plt.style.use('ggplot')
plt.ion() #开启交互模式
draw(a)
for i in range(1,len(a)):
for j in range(i,0,-1):
if a[j]<a[j-1]:
draw(a,j)
a[j],a[j-1]=a[j-1],a[j]
print(a)
draw(a,j)
else:
break
draw(a)
plt.ioff() #关闭交互模式
plt.show()
def draw(a,j=None):
plt.cla() #清屏
x=plt.bar(range(1,len(a)+1),a,width=0.5,color='steelblue')
if j!=None:
x[j].set_color('indianred')
x[j-1].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]
insertion_sort(a)