【发布时间】:2020-06-30 20:49:18
【问题描述】:
我在 Python 3 中编写了一个简短的合并排序算法。我很难理解它是如何实现正确结果的,因为当我尝试跟踪它的逻辑步骤时,我最终会得到一个乱序列表。注释代码如下所示。
我具体指的是代码的合并部分。三个“while”循环。
让我用一个例子来说明什么让我感到困惑。我在注释中解释了细节。
提前感谢您的时间和帮助。
假设我们要合并两个数组。
left = [2,6]
right = [4,8]
def merge_sort(array):
if len(array) > 1:
middle = len(array)//2
left = array[:middle]
right = array[middle:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
# i.e. if 2 < 4
if left[i] < right[j]:
# The first index of the array is assigned the value 2
array[k] = left[i]
# i = 1 now
i += 1
# The 'else' statement is not executed, because the 'if' statement was.
else:
array[k] = right[j]
j += 1
# k = 1 now
k += 1
# The 'while' loop below assigns '6' as the value for index 1 of the array and terminates.
# k = 2 now
while i < len(left):
array[k] = left[i]
i += 1
k += 1
# The last 'while' loop assigns '4' and '8' to indexes 2 and 3 of the array, respectively.
while j < len(right):
array[k] = right[j]
j += 1
k += 1
# The algorithm terminates and from what I can see I should end up with the array of [2,6,4,8].
# I do not, however. It is sorted in ascending order and I cannot see where I'm making a mistake.
【问题讨论】:
-
当你只传入一个列表时,这如何合并两个列表?您的示例与代码的编写方式不一致。
标签: python python-3.x algorithm sorting mergesort