12-謝爾排序
阿新 • • 發佈:2020-11-13
# 我們注意到插入排序的比對次數,在最好的情況下是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)