You are on page 1of 4

Algorithm to merge sorted arrays

In the article we present an algorithm for merging two sorted arrays. One can learn
how to operate with several arrays and master read/write indices. Also, the algorithm
has certain applications in practice, for instance in merge sort.
Merge algorithm
Assume, that both arrays are sorted in ascending order and we want resulting array to
maintain the same order. Algorithm to merge two arrays A[0..m-! and "[0..n-! into
an array #[0..m$n-! is as following%
. Introduce read-indices i, j to traverse arrays A and ", accordingly. Introduce
write-inde& k to store position of the first free cell in the resulting array. "y
default i ' j ' k ' 0.
(. At each step% if both indices are in range )i * m and j * n+, choose minimum of
)A[i!, "[j!+ and write it to #[k!. Otherwise go to step ,.
-. Increase k and inde& of the array, algorithm located minimal value at, by one.
.epeat step (.
,. #opy the rest values from the array, which inde& is still in range, to the resulting
array.
Enhancements
Algorithm could be enhanced in many ways. /or instance, it is reasonable to chec0, if
A[m - ! * "[0! or "[n - ! * A[0!. In any of those cases, there is no need to do more
comparisons. Algorithm could 1ust copy source arrays in the resulting one in the right
order. 2ore complicated enhancements may include searching for interleaving parts
and run merge algorithm for them only. It could save up much time, when si3es of
merged arrays differ in scores of times.
Complexity analysis
2erge algorithm4s time comple&ity is O)n $ m+. Additionally, it re5uires O)n $ m+
additional space to store resulting array.
Code snippets
Java implementation
// size of C array must be equal or greater than
// sum of A and B arrays' sizes
public void merge(int[] A, int[] B, int[] C) {
int i, , !, m, n"
i # $"
# $"
! # $"
m # A%length"
n # B%length"
while (i & m '' & n) {
if (A[i] &# B[]) {
C[!] # A[i]"
i(("
) else {
C[!] # B[]"
(("
)
!(("
)
if (i & m) {
for (int * # i" * & m" *(() {
C[!] # A[*]"
!(("
)
) else {
for (int * # " * & n" *(() {
C[!] # B[*]"
!(("
)
)
)
C++ implementation
// m + size of A
// n + size of B
// size of C array must be equal or greater than
// m ( n
,oid merge(int m, int n, int A[], int B[], int C[]) {
int i, , !"
i # $"
# $"
! # $"
-hile (i & m '' & n) {
if (A[i] &# B[]) {
C[!] # A[i]"
i(("
) else {
C[!] # B[]"
(("
)
!(("
)
if (i & m) {
for (int * # i" * & m" *(() {
C[!] # A[*]"
!(("
)
) else {
for (int * # " * & n" *(() {
C[!] # B[*]"
!(("
)
)
)

You might also like