gpt4 book ai didi

python - 错误的合并排序

转载 作者:行者123 更新时间:2023-12-01 05:13:39 24 4
gpt4 key购买 nike

下面是我的合并函数,它应该类似于CLRS中显示的内容第 31 页。现在我已经注释掉了处理任何剩余列表项的代码。

如果我传递 A = [1, 2, 1, 12, 2, 5] 作为输入。输出为 [1, 2, 1, None, None, None]。

有人能告诉我我做错了什么吗?

def Merge(left, right):
result = [None] * (len(left) + len(right))
i, j, k = 0, 0, 0

while i < len(left) and j < len(right):
if left[i] < right[j]:
result[k] = left[i]
#result.append(left[i])
i += 1
else:
result[k] = right[j]
#result.append(right[j])
j += 1
k += 1

## remaining items in remaining list
## while i < len(left):
## result[k] = left[i]
## i += 1; k+= 1;
##
## while j < len(right):
## result[k] = right[j]
## j += 1; k+= 1;
##
return result

## Ref.: CLRS page 34
def MergeSort(A):
if len(A) > 1:
mid = int(len(A)/2)
left = A[:mid]
right = A[mid:]
MergeSort(left)
MergeSort(right)
return Merge(left, right)
else:
return A

if __name__ == "__main__":
a = [1, 2, 1, 12, 2, 5]
print "a = %s" % a
print "sort a = %s" % MergeSort(a)

最佳答案

当调用MergeSort时,您会递归地返回新列表,但永远不会分配它们:

def Merge(left, right):
result = [None] * (len(left) + len(right))
i, j, k = 0, 0, 0

while i < len(left) and j < len(right):
if left[i] < right[j]:
result[k] = left[i]
#result.append(left[i])
i += 1
else:
result[k] = right[j]
#result.append(right[j])
j += 1
k += 1

## remaining items in remaining list
## while i < len(left):
## result[k] = left[i]
## i += 1; k+= 1;
##
## while j < len(right):
## result[k] = right[j]
## j += 1; k+= 1;
##
return result

## Ref.: CLRS page 34
def MergeSort(A):
if len(A) > 1:
mid = int(len(A)/2)
left = A[:mid]
right = A[mid:]
#MergeSort(left)
# here should be
left = MergeSort(left)
#MergeSort(right)
# here should be
right = MergeSort(right)
return Merge(left, right)
else:
return A

if __name__ == "__main__":
a = [1, 2, 1, 12, 2, 5]
print "a = %s" % a
print "sort a = %s" % MergeSort(a)

关于python - 错误的合并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23655216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com