选择排序
输出结果:
选择排序:
[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)