希尔排序
输出结果:
希尔排序:
[3, 2, 9, 7, 1, 6]
[1, 2, 9, 7, 3, 6]
[1, 2, 7, 9, 3, 6]
[1, 2, 7, 3, 9, 6]
[1, 2, 3, 7, 9, 6]
[1, 2, 3, 7, 6, 9]
[1, 2, 3, 6, 7, 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 shell_sort(a):
print('希尔排序:')
plt.figure()
plt.style.use('ggplot')
plt.ion() #开启交互模式
draw(a)
h=1
while h<len(a)/3:
h=3*h+1
print(a)
while h>=1:
for i in range(h,len(a)):
j=i
while j>=h and a[j]<a[j-h]:
draw(a,j,h)
a[j],a[j-h]=a[j-h],a[j]
draw(a,j,h)
j-=h
print(a)
draw(a,j,h)
h=h//3
print(a)
draw(a)
def draw(a,j=None,h=None):
plt.cla() #清屏
x=plt.bar(range(1,len(a)+1),a,width=0.5,color='steelblue')
if j!=None and h!=None:
x[j].set_color('indianred')
x[j-h].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]
shell_sort(a)