我已经实现了一个有效的合并排序:
def merge_sort(alist):
length = len(alist)
if length < 2:
return
mid = length // 2
left = alist[:mid]
right = alist[mid:]
merge_sort(left)
merge_sort(right)
return merge(left, right, alist)
def merge(left, right, alist):
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
alist[k] = left[i]
i += 1
else:
alist[k] = right[j]
j += 1
k += 1
while i < len(left):
alist[k] = left[i]
k += 1
i += 1
while j < len(right):
alist[k] = right[j]
k += 1
j += 1
return alist
print(merge_sort([5,3,4,2,1,6]))
但是,如果删除了left
和right
变量,并且它们的所有实例都直接替换了它们的值,那么它就会停止工作(merge
方法不会更改):
def merge_sort(alist):
length = len(alist)
if length < 2:
return
mid = length // 2
merge_sort(alist[:mid])
merge_sort(alist[mid:])
return merge(alist[:mid], alist[mid:], alist)
有人可以解释一下导致这种情况的原因吗?
答案 0 :(得分:2)
alist[:mid]
和alist[mid:]
分别制作列表的副本。当您在调用merge
时再次执行此操作时,您将另一个副本排除。