# 我们注意到插入排序的比对次数,在最好的情况下是O(n),这种情况发生在列表已是有序的情况下,
# 实际上,列表越接近有序,插入排序的比对次数就越少
# 从这个情况入手,谢尔排序以插入排序作为基础,对无序表进行间隔划分子列表,每个子列表都执行插入排序
# 子列表的间隔一般从n/2开始,每趟倍增:n/4, n/8......直到1
# 谢尔排序的时间复杂度约为O(n**1.5)
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
def shellSort(alist):
sublistcount = len(alist) // 2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(alist, startposition, sublistcount)
sublistcount = sublistcount // 2
testlist = [2, 3, 3, 243, 24, 24455, 23]
shellSort(testlist)
print(testlist)