排序和查找
一、知識概覽
本章主要講解六種排序算法中的插入排序和謝爾排序,知識概覽如下:
1.1 插入排序算法
1.2 謝爾排序
二、代碼實現
2.1插入排序
# 插入排序
def insertionSort(alist):
# index是待插入項位置
for index in range(1, len(alist)):
# 新項
currentvalue = alist[index]
pos = index
while pos > 0 and alist[pos - 1] > currentvalue:
# 倒着依次和前一項比較
alist[pos] = alist[pos - 1]
pos = pos - 1
# pos指向第一個比插入項小的項後面的位置
alist[pos] = currentvalue
return alist
2.2 謝爾排序
# 謝爾排序
def shellSort(alist):
# 間隔設定
sublistcount = len(alist) // 2
while sublistcount > 0:
# 子列表排序
for startpos in range(sublistcount):
# 帶間隔的插入排序
gapinsertionSort(alist, startpos, sublistcount)
print("After increment of size", sublistcount, "The list is", alist)
sublistcount = sublistcount // 2
return alist
def gapinsertionSort(alist, start, gap):
for i in range(start + gap, len(alist), gap):
currentvalue = alist[i]
pos = i
while pos >= gap and alist[pos - gap] > currentvalue:
alist[pos] = alist[pos - gap]
pos = pos - gap
alist[pos] = currentvalue
lista = [17, 26, 93, 44, 77, 31, 54, 55, 20]
lista1 = insertionSort(lista)
lista2 = shellSort(lista)
print(lista1)
print(lista2)
2.3 輸出
After increment of size 4 The list is [17, 20, 26, 31, 44, 54, 55, 77, 93]
After increment of size 2 The list is [17, 20, 26, 31, 44, 54, 55, 77, 93]
After increment of size 1 The list is [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]