-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellSort.py
More file actions
53 lines (52 loc) · 1.47 KB
/
shellSort.py
File metadata and controls
53 lines (52 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#coding=utf-8
"""
Written by zxcode-123
------------------------------------------------------------
Usage:希尔排序
"""
from generateNearlyOrdered import generateNearlyOrderedArray
# 方法一
def shellSort(alist):
length = len(alist)
n = length//2
while(n>0):
for i in range(n,length):
temp = alist[i]
for j in range(i,-1,-n):
if(j<0):
break
if(temp < alist[j-n]):
alist[j] = alist[j-n]
else:
break
alist[j] = temp
n = n//2
return alist
# --------------------------------------------------------------------
# 方法二
def shellSort1(alist):
n = len(alist)
gap = n//2
while(gap>0):
for i in range(gap):
gapInsetionSort(alist, i, gap)
gap = gap//2
return alist
# start子数列开始的起始位置, gap表示间隔
# 希尔排序的辅助函数
def gapInsetionSort(alist, start , gap):
for i in range(start+gap,len(alist),gap):
temp = alist[i]
position = i
while position > start and alist[position-gap]>temp:
alist[position] = alist[position-gap]
position = position-gap
alist[position] = temp
def test():
arr = generateNearlyOrderedArray(10,10)
print(arr)
alist = shellSort1(arr)
print("------------------------------------------")
print(alist)
if __name__ == '__main__':
test()