我正在尝试自行实现mergeSort,但是返回列表的顺序仍然不正确。我一定缺少某些东西(尤其是在合并步骤中),有人可以帮我什么吗?
这是我的代码:
def merge(left_half, right_half):
"""
Merge 2 sorted lists.
:param left_half: sorted list C
:param right_half: sorted list D
:return: sorted list B
"""
i = 0
j = 0
B = []
for item in range(len(left_half) + len(right_half)):
while i < len(left_half) and j < len(right_half):
if left_half[i] <= right_half[j]:
B.insert(item, left_half[i])
i += 1
else:
B.insert(item, right_half[j])
j += 1
B += left_half[i:]
B += right_half[j:]
print("result: ", B)
return B
def mergeSort(A):
"""
Input: list A of n distinct integers.
Output: list with the same integers, sorted from smallest to largest.
:return: Output
"""
# base case
if len(A) < 2:
return A
# divide the list into two
mid = len(A) // 2
print(mid)
left = A[:mid] # recursively sort first half of A
right = A[mid:] # recursively sort second half of A
x = mergeSort(left)
y = mergeSort(right)
return merge(x, y)
print(mergeSort([1, 3, 2, 4, 6, 5]))
在最后一次合并之前,我正确地收到了两个列表[1、2、3]和[4、5、6],但是我的最终结果是[3、2、1、4、5、6]。
答案 0 :(得分:0)
在for循环的第一次迭代中,您将完全遍历列表中的一个,但始终在索引insert
处0
。
您不想insert
一个元素,而您总是想append
一个元素。这样就不必进行for循环了。
这是您代码的固定版本:
def merge(left_half, right_half):
"""
Merge 2 sorted arrays.
:param left_half: sorted array C
:param right_half: sorted array D
:return: sorted array B
"""
i = 0
j = 0
B = []
while i < len(left_half) and j < len(right_half):
if left_half[i] <= right_half[j]:
B.append(left_half[i])
i += 1
else:
B.append(right_half[j])
j += 1
B += left_half[i:]
B += right_half[j:]
print("result: ", B)
return B
merge([1, 2, 3], [4, 5, 6])
# result: [1, 2, 3, 4, 5, 6]