我正在尝试使用这种合并排序算法,我完全不知道为什么它不会。合并函数似乎工作正常,但sort函数似乎不起作用。我已经在网上搜索了一个解决方案,但我似乎无法找出我做错了什么。我应该提一下,我对python和编码很新,所以任何帮助都会受到赞赏。 python代码如下:
def sort(sorted_list):
if len(sorted_list) <= 1:
return sorted_list
middle = len(sorted_list) // 2
left = sorted_list[:middle]
right = sorted_list[middle:]
left = sort(left)
right = sort(right)
return sorted_list(merge(left, right))
def merge(a_list, b_list):
combined_list = []
index_a = 0
index_b = 0
length_a = len(a_list)
length_b = len(b_list)
while index_a < length_a or index_b < length_b:
if index_a < length_a and index_b < length_b:
if a_list[index_b] <= b_list[index_b]:
combined_list += [a_list[index_a]]
index_a = index_a + 1
else:
combined_list += [b_list[index_b]]
index_b = index_b + 1
elif index_a < length_a:
combined_list += [a_list[index_a]]
index_a = index_a +1
else:
combined_list += [b_list[index_b]]
index_b = index_b + 1
return combined_list
答案 0 :(得分:1)
这是错的:
return sorted_list(merge(left, right))
应该是:
return merge(left, right)
此外,与您的错误无关,但应更正此行:
if a_list[index_b] <= b_list[index_b]:
于:
if a_list[index_a] <= b_list[index_b]:
答案 1 :(得分:0)
我已对您的计划进行了多次修复。这是固定程序。
def sort(sorted_list):
if len(sorted_list) <= 1:
return sorted_list
middle = len(sorted_list) // 2
left = sorted_list[:middle]
right = sorted_list[middle:]
left = sort(left)
right = sort(right)
return merge(left, right)
def merge(a_list, b_list):
combined_list = []
index_a = 0
index_b = 0
length_a = len(a_list)
length_b = len(b_list)
while index_a < length_a and index_b < length_b:
if a_list[index_a] <= b_list[index_b]:
combined_list.append(a_list[index_a])
index_a = index_a + 1
else:
combined_list.append(b_list[index_b])
index_b = index_b + 1
while index_a < length_a:
combined_list.append(a_list[index_a])
index_a = index_a + 1
while index_b < length_b:
combined_list.append(b_list[index_b])
index_b = index_b + 1
return combined_list
print sort([5,1,2])