04. 希尔排序 #80
Replies: 9 comments 4 replies
-
7 line 需要对间隔为gap的数据进行插入排序 第7行应该为 range(0,size,gap) |
Beta Was this translation helpful? Give feedback.
-
这应该是两种写法。
这里的第 7 ~ 20 行每遍历一次,就是对每组内元素进行了插入排序。并不存在重复计算。 而另一种每次增加 gap 的遍历(即 range(0, size, gap))则需要再套一层循环(即 range(0, gap))对分组下进行插入排序。 |
Beta Was this translation helpful? Give feedback.
-
理解了 确实是两个思路不一样 谢谢 |
Beta Was this translation helpful? Give feedback.
-
public class Solution {
public int[] shellSort(int[] arr) {
int size = arr.length;
int gap = size / 2;
while (gap > 0) {
for (int i = gap; i < size; i++) {
int temp = arr[i];
int j = i;
while (j >= gap && arr[j - gap] > temp) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = temp;
}
gap = gap / 2;
}
return arr;
}
public int[] sortArray(int[] nums) {
return shellSort(nums);
}
} |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
博主,有个问题想请教下,这里的gap参数应该指的是下标位置的固定间隔数是吧?因为我看到过程图中的真实元素间隔数 = gap - 1 |
Beta Was this translation helpful? Give feedback.
-
总觉得j = i有点奇怪,这样是不是清楚一些。 def shell_sort(lst):
gap = len(lst) // 2
while gap >= 1:
for i in range(gap,len(lst)): # i:抽出固定与其他牌比较的牌
j = i - gap # 与i进行比较的牌
temp = lst[i]
while j >= 0 and lst[j] > temp:
lst[j+gap] = lst[j]
j -= gap
else:
lst[j+gap] = temp
gap = gap // 2
return lst
lst = [7,2,6,8,0,4,1,5,9,3]
print(shell_sort(lst)) |
Beta Was this translation helpful? Give feedback.
-
竟然有人看😲好嘞辛苦
ITCharge ***@***.***>于2024年8月2日 周五上午9:01写道:
… 这个粘贴缩进全没了,铸币啊
没事,我帮你改一下
—
Reply to this email directly, view it on GitHub
<#80 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/BFTAO575LKNEQ6BN23N4HY3ZPLK7FAVCNFSM6AAAAABL243MXKVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTAMRRG44DSNY>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
def shell(lst):
gap = len(lst) // 2
while gap > 0:
for i in range(gap,len(lst)):
temp = lst[i]
j = i - gap
while j >= 0 and lst[j] > temp:
lst[j+gap] = lst[j]
j -= gap
else:
lst[j+gap] = temp
gap = gap // 2
return lst
lst = [7,2,6,8,0,4,1,5,9,3]
print(shell(lst)) |
Beta Was this translation helpful? Give feedback.
-
04. 希尔排序 | 算法通关手册
https://algo.itcharge.cn/01.Array/02.Array-Sort/04.Array-Shell-Sort/
Beta Was this translation helpful? Give feedback.
All reactions