Skip to content

Commit 639eecf

Browse files
authored
Create Shell_sort.py
1 parent 81fc74a commit 639eecf

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

‎Sorting/Shell_sort.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Shell Sort
2+
data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]
3+
4+
def ShellSort(data):
5+
n = len(data) # 獲取data長度
6+
gap = n // 2 # 初始化間隔,設為數組長度的一半
7+
while gap > 0: # 當間隔大於0時循環
8+
for i in range(gap, n): # 從間隔位置開始遍歷數組
9+
temp = data[i] # 暫存當前元素
10+
j = i # 設置 j 為當前索引
11+
while j >= gap and data[j-gap] > temp: # 如果 j 大於等於間隔且前一個間隔的元素大於暫存元素
12+
data[j] = data[j-gap] # 將前一個間隔的元素移到當前位置
13+
j = j - gap # 將 j 向前移動一個間隔
14+
data[j] = temp # 將暫存元素放到正確位置
15+
gap = gap // 2 # 縮小間隔
16+
return data # 返回排序後的數據
17+
18+
print(ShellSort(data)) # 印排序結果
19+
# 輸出: [23, 23, 29, 34, 55, 66, 67, 78, 78, 79, 88, 89, 92, 96, 96, 100]

0 commit comments

Comments
 (0)