Merging
Merging means combining two sets of data which have already been sorted in such a way
that the result is also sorted. For example, when you merge the lists 2 6 9 10 15 and 4 8 12,
the result should be 2 4 6 8 9 10 12 15.
When you are merging two lists, you should decide whether the duplicates should be
eliminated or not. For instance, if you are trying to merge students of two sections according
to their grades, duplicates must be repeated, because we don't want to lose students on the
way, just because they got the same grade.
There are two ways of merging two arrays. One is to use a separate array to store the
merged list. The other way is to store the merged list in one of the two arrays. Now, you will
learn the algorithms for both merging methods, starting with the first one.
Merging into a Separate Array
This algorithm merges the elements of two sorted arrays and uses another array to store the
merged values.
For instance, assume that the arrays to be sorted are A and B arrays, and the result will be
put into the C array as below, thus without duplicates.
A B C
3 1 1
static int mergeIntoC(int[] A, int sizeA, int[] B,
4 2 2 int sizeB, int[] C) {
8 4 3 int kA = 0, kB = 0, kC = 0;
10 8 4 while (kA < sizeA && kB < sizeB) {
8
15 if (A[kA] < B[kB])
10
C[kC++] = A[kA++];
15
else if (B[kB] < A[kA])
C[kC++] = B[kB++];
else {
C[kC++] = A[kA++];
kB++;
}
}
while (kA < sizeA)
C[kC++] = A[kA++];
while (kB < sizeB)
C[kC++] = B[kB++];
return kC;
}
Merging 1
How can we change our method so that the array C will contain the duplicates? If the same
value is matched in both arrays, both of them should be put into the C array.
{
C[kC++] = A[kA++];
C[kC++] = B[kB++];
}
Notice that, we don’t need sizeC as an output parameter any more, because the size of the
resultant array will be sizeA + sizeB.
Merging 2