Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

MERGING OF ARRAYS

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

Q1. What is the time complexity of the


above discussed algorithm for
merging?
Reflection Spot Pause the video for a minute, Think
and Write

Q1. What is the time complexity of the


above discussed algorithm for
merging?

Ans: The time complexity is O(n2).


Because in this algorithm the contents
of two arrays are copied one after the
other and sorted. The worst case time
taken for sorting is O(n2).
MERGING – Algorithm 2
1. Input two sorted arrays a[ ] and b [ ]. Let c[ ] be the output array
2. Let i, j be the pointers to arrays a[] and b[].
3. while (i < n) and ( j < n ) do
(a) compare a[i] and b[j] then merge the smaller member of the
pair into c array,
(b) update appropriate pointers,
4. if i<m then
(a) copy rest of a array into c,
else
(a') copy rest of b array into c.
MERGING - Example

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

if(a[i] < b[j]) c[k++]=b[j++];


c[k++]=a[i++]; }
else // copy b[ ] into output array // print the 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)

You might also like