Merging of Arrays: Dr. S. Ponmalar Assistant Professor, Thiagarajar College of Engineering Madurai
Merging of Arrays: Dr. S. Ponmalar Assistant Professor, Thiagarajar College of Engineering Madurai
PRESENTED BY
DR. S. PONMALAR
ASSISTANT PROFESSOR,
THIAGARAJAR COLLEGE OF ENGINEERING
MADURAI
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
MERGING OF ARRAYS
PROBLEM STATEMENT:
Merge two arrays of integers, both with their elements in
ascending order, into a single ordered array.
MERGING – Algorithm 1
1. Input array a[ ] and b[ ]. Declare resultant array c[ ]
2. Copy contents of a[ ] into resultant array c[ ]
3. Copy content of b[ ] at the end of c[ ]
4. Sort the resultant array c[ ]
Reflection Spot
Pause the video for a minute, Think
and Write
i j k
i j k
MERGING – Example contd…
i j k
MERGING EXAMPLE contd.
i j k
PROGRAM FOR MERGING
#include<stdio.h> while(i<n1)
void main() {
// copy any remaining element in a1 into output array
{
int a[ ]={1,2,9}, b[ ]={3,4,5,11}, c[7]; c[k++]=a[i++];
int i=0, j=0, k=0, i,n1=3,n2=4; }
while(i<n1 && j<n2) while(j<n2)
{ {
// a[i] is less, copy a[ ] into output array // copy any remaining element in a1 into output array
c[k++]=b[j++]; for(i=0;i<k;i++)
} printf("%d\t",c[i] );
}
COMPLEXITY OF MERGING ALGORITHM 2
• Time complexity = O(n+m) = O(n) n - no. of elements in array1
m – no. of elements in array2
• Space Complexity = s(n+m)