插入排序的比对次数,在最好的情况下是O(n),这种情况发生在列表已是有序的情况下,实际上,列表越接近有序,插入排序的比对次数就越少
从这个情况分析,希尔排序以插入排序作为基础,对无序表进行“间隔”划分子列表,每个子列表都执行插入排序
最后一趟是标准的插入排序,但由于前面几趟已经将列表处理到接近有序,这一趟仅需少数几次移动即可完成
子列表的间隔一般从n/2开始,每趟倍增:n/4, n/8,…,1
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", list)
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
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
shellSort(alist)
print(alist)
时间复杂度O(n^(1.3—2))