为什么这种并行合并算法不起作用?
对于给定的两个排序数组A和B,我想设计一个并行算法将它们合并到一个排序数组C中。
我是参考以下页面写的。
本质上,它是一种可以并行或顺序执行的算法。我正在尝试暂时编写顺序合并算法。 我该如何修复这个程序?
#coding: utf-8
def binary_search(x, A, left, right):
begin = left
end = right
while begin < end:
middle = (begin + end) / 2
if x <= A[middle]:
end = middle
else:
begin = middle + 1
return end
def merge(A, B, C, R1, R2, R3):
[[p1, r1], [p2, r2], [p3, r3]] = [R1, R2, R3]
m = r1 - p1
n = r2 - p2
if m < n: # ensure thet m >= n
A, B = B, A
m, n = n, m
[p1, r1], [p2, r2] = R2, R1
if m <= 0: # both empty?
return
q1 = (p1 + r1) / 2
q2 = binary_search(A[q1], B, p2, r2)
q3 = p3 + (q1 - p1) + (q2 - p2)
C[q3] = A[q1]
merge(A, B, C, [p1, q1-1], [p2, q2-1], [p3, q3])
merge(A, B, C, [q1+1, r1], [q2, r2], [q3+1, r3])
A = [2,3,7,8,11,16]
B = [1,5,7,10,15,19]
C = [0 for i in range(len(A)+len(B))]
merge(A, B, C, [0, len(A)-1], [0, len(B)-1], [0, len(C)-1])
print C
答案 0 :(得分:1)
问题在于以下陈述
if m <= 0: # both empty?
return
您没有处理1个元素数组的合并。
以下代码有效并添加了一些解释更改的注释。这可能是一个起点。
#coding: utf-8
from math import ceil
def binary_search(x, A, left, right):
begin = left
end = right
while begin < end:
middle = (begin + end) / 2
if x <= A[middle]:
end = middle
else:
begin = middle + 1
return end
def merge(A, B, C, R1, R2, R3):
[[p1, r1], [p2, r2], [p3, r3]] = [R1, R2, R3]
m = r1 - p1
n = r2 - p2
if m < n: # ensure thet m >= n
A, B = B, A
m, n = n, m
[p1, r1], [p2, r2] = R2, R1
if m <= 0:
# 1 elements in both the array. Merge in proper order
if m == 0 and n == 0:
q3 = p3
if A[p1] < B[p1]:
C[q3] = A[p1]
C[q3+1] = B[p2]
else:
C[q3] = B[p2]
C[q3+1] = A[p1]
# 1 elements in A array.
elif m == 0:
C[p3] = A[p1]
return
q1 = (p1+r1)/2
q2 = binary_search(A[q1], B, p2, r2)
q3 = p3 + (q1 - p1) + (q2 - p2)
C[q3] = A[q1]
merge(A, B, C, [p1, q1-1], [p2, q2-1], [p3, q3])
merge(A, B, C, [q1+1, r1], [q2, r2], [q3+1, r3])
A = [2,3,7,8,11,16]
B = [1,5,7,10,15,19]
print A
print B
C = [0 for i in range(len(A)+len(B))]
merge(A, B, C, [0, len(A)-1], [0, len(B)-1], [0, len(C)-1])
print C
希望它有所帮助!
答案 1 :(得分:0)
对于任何仍然感兴趣的人(我碰巧在同一个 wiki 页面上遇到了同样的问题),页面上的算法似乎是不正确的。它改编自《算法导论》(一本可以在网上很容易找到的书)。正确的实现在这里: Introduction to Algorithms Page 800, P-Merge