希尔排序是插入排序的一个变种,插入排序是比较步长为1,而希尔排序的比较步长则不只是1,通常情况下是一个数组,数组不同则时间复杂度不同。
来看代码:
#!/bin/python
import sys
n = len(sys.argv) - 1
gaps = [72, 36, 24, 18, 12, 9, 8, 6, 4, 3, 2, 1]
for gap in gaps:
for i in range(gap + 1, n + 1):
j = i
tmp = sys.argv[i]
while(int(tmp, 10) < int(sys.argv[j - gap], 10)):
sys.argv[j] = sys.argv[j - gap]
j = j - gap
if(j <= gap):
break
sys.argv[j] = tmp
print sys.argv
用以上的算法对数列[4, 2, 3, 10, 1, 7, 8, 21],过程如下:
['./shell.py', '4', '2', '3', '10', '1', '7', '8', '21']
['./shell.py', '4', '2', '3', '10', '1', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']