以下代码基于:
第一次左右合并得到中间结果
下一个合并中间结果和中间结果
代码
def Merge3Way(left,middle,right):
"""Takes three lists that are sorted in decreasing order and merges them into
one list ordered largest to smallest"""
# Step 1: Merge left & right
res_1 = []
left_ind, right_ind = 0, 0
while left_ind < len(left) and right_ind < len(right):
if left[left_ind] > right[right_ind]:
res_1.append(left[left_ind])
left_ind += 1
else:
res_1.append(right[right_ind])
right_ind += 1
for left_ind in range(left_ind, len(left)):
res_1.append(left[left_ind])
for right_ind in range(right_ind, len(right)):
res_1.append(left[right_index])
# Step 2: Merge intermediate result and middle
res_2 = []
res_ind, middle_ind = 0, 0
while res_ind < len(res_1) and middle_ind < len(middle):
if res_1[res_ind] > middle[middle_ind]:
res_2.append(res_1[res_ind])
res_ind += 1
else:
res_2.append(middle[middle_ind])
middle_ind += 1
for res_ind in range(res_ind, len(res_1)):
res_2.append(res_1[res_ind])
for middle_index in range(middle_ind, len(middle)):
res_2.append(middle[middle_ind])
return res_2
试验
result = Merge3Way([3,2,1],[6,5,4],[9,8,7])
print(result)
# Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]