Shell排序属于插入排序, 增量为1的Shell排序就是直接插入排序
设增量用h表示,Shell排序就是 将数组分为k = (len-1)/h组, 每组为i + n*h 序列 (n为整数 , n=[0,k-1],i=[0,k-1] )
即分成序列:
0,h,2*h......
1,1+h , 1+ 2*h.....
2, 2 +h, 2 + 2* h...
....
i , i + h, i +2*h....
分别为这些序列进行插入排序,再重新计算h值排序
增量公式有许多,这里使用 h = 3 * h +1
#Shell排序 class ShellSort: def sort(self,arrData): length = len(arrData); h = 1; while h < length/3: h = h*3 +1; while h>0: i = h; while i < length: if arrData[i] < arrData[i-h]: #保存arrData[i]以免被覆盖 tmp = arrData[i]; j = i - h; #整体向后移动, while j>=0 and arrData[j] > tmp: arrData[j + h] = arrData[j]; j = j - h; arrData[j + h] = tmp; i = i + 1; print(arrData); h = (h-1)//3; return; shellSort = ShellSort(); shellSort.sort([7,2,5,3,1,8,6,100,48,38,45,20,34,67,12,23,90,58]);