介紹
希爾排序,也稱遞減增量排序算法,實質是分組插入排序。由 Donald Shell 於1959年提出。希爾排序是非穩定排序算法。
希爾排序的基本思想是:將數組列在一個表中並對列分別進行插入排序,重複這過程,不過每次用更長的列(步長更長了,列數更少了)來進行。最後整個表就只有一列了。將數組轉換至表是爲了更好地理解這算法,算法本身還是使用數組進行排序。
例如,假設有這樣一組數[ 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10 ],如果我們以步長爲5開始進行排序,我們可以通過將這列表放在有5列的表中來更好地描述算法,這樣他們就應該看起來是這樣:
13 14 94 33 82
25 59 94 65 23
45 27 73 25 39
10
然後我們對每列進行排序:
10 14 73 25 23
13 27 94 33 39
25 59 94 65 82
45
將上述四行數字,依序接在一起時我們得到:[ 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 ]。這時10已經移至正確位置了,然後再以3爲步長進行排序:
10 14 73
25 23 13
27 94 33
39 25 59
94 65 82
45
排序之後變爲:
10 14 13
25 23 33
27 25 59
39 65 73
45 94 82
94
最後以1步長進行排序(此時就是簡單的插入排序了)。
代碼
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 17:08:17 2016
@author: zang
"""
from matplotlib import pyplot as plt
import random
def shellSort(ary):
n = len(ary)
gap = int(round(n/2)) #初始步長 , 用round四捨五入取整
while gap > 0 :
for i in range(gap,n): #每一列進行插入排序 , 從gap 到 n-1
temp = ary[i]
j = i
while ( j >= gap and ary[j-gap] > temp ): #插入排序
ary[j] = ary[j-gap]
j = j - gap
ary[j] = temp
gap = int(round(gap/2)) #重新設置步長
return ary
def plotScatter(inputList):
plt.scatter(range(len(inputList)),inputList)
plt.show()
if __name__ == "__main__":
num_list = range(1000)
unsortedList = random.sample(num_list, 30)
print "unsortedList:"
plotScatter(unsortedList)
print unsortedList
sortedList = shellSort(unsortedList)
print "sortedList:"
plotScatter(sortedList)
print sortedList
測試
輸入
[84, 378, 602, 966, 54, 98, 749, 51, 735, 883, 326, 580, 506, 572, 59, 183, 493, 337, 246, 421, 115, 149, 784, 529, 207, 574, 176, 614, 855, 121]
輸出
[51, 54, 59, 84, 98, 115, 121, 149, 176, 183, 207, 246, 326, 337, 378, 421, 493, 506, 529, 572, 574, 580, 602, 614, 735, 749, 784, 855, 883, 966]
分析
情況 | 性能 |
---|---|
Worst case performance: | – |
Best case performance: | |
Average case performance: | |
Worst case space complexity: |