Merging sorted sequences
Given are two sorted arrays A,B
of n integers (assume all of them are distinct).
The task is to compute a sorted array containg all elements from A
and B
/
The simplest sequential way is as follows:
input int A[_], B[_];
int n = A.size, m = B.size;
output int C[n + m];
int i = 0, j = 0, k = 0;
while (i < n || j < m)
if (i == n)
C[k++] = B[j++];
else if (j == m)
C[k++] = A[i++];
else if (A[i] < B[j])
C[k++] = A[i++];
else
C[k++] = B[j++];
A
O(log n) time and linear work algorithm is as follows:
int merge(int A[_], int B[_], int offs) {
int n = A.size, m = B.size;
// if sizes are small, just merge sequentially
if (A.size <= bs && B.size <= bs)
merge_seq(A,B,offs);
else {
int k = 1 + (n - 1) / bs;
int X[k];
pardo(i : k) X[i] = binary_search(A[i * bs], B);
// copy elemets from B smaller than any of A
if (X[0] > 0) pardo(i : X[0]) C[i + offs] = B[i];
pardo(i : k) {
int nn = bs;
if (i == k - 1) nn = n - i * bs;
int AA[nn];
pardo(j : nn) AA[j] = A[i * bs + j];
int top = m;
if (i < k - 1) top = X[i + 1];
int mm = top - X[i];
if (mm == 0)
pardo(j : nn) C[offs + i * bs + j + X[i]] = AA[j];
else {
int BB[mm];
pardo(j : mm) BB[j] = B[X[i] + j];
merge(BB, AA, offs + i * bs + X[i]);
}
}
}
}