forked from itcharge/AlgoNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray-ShellSort.py
More file actions
26 lines (24 loc) · 974 Bytes
/
Array-ShellSort.py
File metadata and controls
26 lines (24 loc) · 974 Bytes
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
class Solution:
def shellSort(self, nums: [int]) -> [int]:
size = len(nums)
gap = size // 2
# 按照 gap 分组
while gap > 0:
# 对每组元素进行插入排序
for i in range(gap, size):
# temp 为每组中无序数组第 1 个元素
temp = nums[i]
j = i
# 从右至左遍历每组中的有序数组元素
while j >= gap and nums[j - gap] > temp:
# 将每组有序数组中插入位置右侧的元素依次在组中右移一位
nums[j] = nums[j - gap]
j -= gap
# 将该元素插入到适当位置
nums[j] = temp
# 缩小 gap 间隔
gap = gap // 2
return nums
def sortArray(self, nums: [int]) -> [int]:
return self.shellSort(nums)
print(Solution().sortArray([7, 2, 6, 8, 0, 4, 1, 5, 9, 3]))