我正在尝试在 python 中实现合并排序,如下所示:
def MergeSortTopdown(list_n):
#Base condition to stop recursion
if len(list_n) == 1:
return list_n
else:
mid = int(len(list_n)/2)
first_half = list_n[:mid]
second_half = list_n[mid:]
MergeSortTopdown(first_half)
MergeSortTopdown(second_half)
i = 0
j = 0
n = len(list_n)
for k in range(n):
if j >= len(first_half) and i < len(second_half):
list_n[k] = first_half[i]
i += 1
if i >= len(first_half) and j < len(second_half):
list_n[k] = second_half[j]
j += 1
if i < len(first_half) and j < len(second_half):
if first_half[i] > second_half[j]:
list_n[k] = second_half[j]
j += 1
elif second_half[j] > first_half[i]:
list_n[k] = first_half[i]
i += 1
elif second_half[i] == first_half[j]:
list_n[k] = first_half[i]
if i>j:
i += 1
else:
j += 1
return list_n
当我用已经排序的列表进行测试时,这似乎是合理的。但是,当我运行时,会出现此错误:
MergeSortTopdown([3,4,6,7,1,8,56,112,67])
Traceback (most recent call last):
File "<ipython-input-11-29db640f4fc6>", line 1, in <module>
MergeSortTopdown([3,4,6,7,1,8,56,112,67])
File "C:/Users/Emmanuel Hoang/MergeSortTopDown.py", line 13, in MergeSortTopdown
MergeSortTopdown(second_half)
File "C:/Users/Emmanuel Hoang/MergeSortTopDown.py", line 13, in MergeSortTopdown
MergeSortTopdown(second_half)
File "C:/Users/Emmanuel Hoang/MergeSortTopDown.py", line 19, in MergeSortTopdown
list_n[k] = first_half[i]
IndexError: list index out of range
你能告诉我我的代码有什么问题吗,有什么办法可以改进我的代码。先感谢您
慕丝7291255
POPMUISE
相关分类