插入选择和希尔选择
代码如下:
'''#插入选择
def insertionSort(alist):
for i in range(1,len(alist)):
temp = alist[i]
position = i
while position>0 and alist[i-1]>temp:
alist[position] = alist[position-1]
position -=1
alist[position] = temp
'''
#希尔选择
def shellSort(alist):
gap = 1 #选取划分间隔为2
num = len(alist)//gap
for i in range(num):
for j in range(i+gap,len(alist),gap):
current = alist[j]
position = j
while position>=gap and alist[position-gap]>current:
alist[position] = alist[position-gap]
position = position-gap
alist[position] = current
print(alist)
alist = [54,26,93,17,77,31,44,55,20]
shellSort(alist)
运行结果为:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
网友评论