希尔排序
算法原理:希尔排序根据一定的间隔将列表分成几个小部分,然后对每个小部分采用插入排序。通过对几个小部分进行排序后,整个列表变得比以前有序得多。
来上面的排序结果我们再采用插入排序来处理成我们想要的结果,注意到,经过上面的排序后,插入排序需要的 shifting少了很多。
def shellSort(alist):
sublistcount = len(alist) // 2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(alist,startposition,sublistcount)
print("After increments of size",sublistcount,"The list is",alist)
sublistcount = sublistcount // 2
def gapInsertionSort(alist,start,gap):
for i in range(start+gap,len(alist),gap):
currentvalue = alist[i]
position = i
# 使用插入法对当前小块中的数据进行排序
while position >= gap and alist[position-gap] > currentvalue:
alist[position] = alist[position - gap]
position = position - gap
alist[position] = currentvalue
Reference:
http://interactivepython.org/courselib/static/pythonds/SortSearch/TheShellSort.html