我已经从PseudoCode构建了一个shell排序算法,并在Python脚本中构建了C代码。
(我正在通过算法练习)
我似乎无法让排序列表返回
当我打印(内部)作为循环的一部分时,它确实按1:1的顺序打印出来并结束..
2 3 4 五 6 7 8 9
我试图从函数
返回内部我得到的反应[[9]]
这是最后一次迭代..所以我知道它迭代,正确排序..
但是我无法让它返回排序列表
[1,2,3,4,5,6,7,8,9]
unsort_list = [4, 6, 3, 2, 1, 9, 7, 8, 5]
def shell(a):
"""
Step 1 − Initialize the value of h
Step 2 − Divide the list into smaller sub-list of equal interval h
Step 3 − Sort these sub-lists using insertion sort
Step 3 − Repeat until complete list is sorted
"""
interval_h = 1
i = 0
l = len(a)
elements = a
inner = []
outer = []
value_ins = []
print(l)
while interval_h <= l / 3:
interval_h = interval_h * 3 + 1
while interval_h > 0:
outer = interval_h
for i in elements:
while outer < i:
outer += 1
value_ins = [outer]
inner = outer
while inner > interval_h - 1 and [inner - interval_h] >= value_ins:
inner = [inner - interval_h]
inner -= interval_h
inner = value_ins
interval_h = (interval_h - 1)
i += 1
return inner
sorted_list = [shell(unsort_list)]
print(sorted_list)
答案 0 :(得分:1)
在接受上述建议后经过多次剥离和重建后,我使用枚举来解决这个问题。
感谢您的建议
def maf_shell(a):
"""
Step 1 − Initialize the value of h
Step 2 − Divide the list into smaller sub-list of equal interval (h)
Step 3 − Sort these sub-lists using insertion sort
Step 3 − Repeat until complete list is sorted
"""
interval = len(a) // 2
while interval:
for i, j in enumerate(a):
while i >= interval and a[i - interval] > j:
a[i] = a[i - interval]
i -= interval
a[i] = j
interval = 1 if interval == 2 else int(interval * 5.0 / 11)
unsort_list = [4, 6, 3, 2, 1, 9, 7, 8, 5]
maf_shell(unsort_list)
print(unsort_list)