Monday, October 31, 2016

Merging Elements of Two Sorted Arrays Into One Sorted Array

Tags

Merging is done by comparing the first elements of sorted arrays and the inserting the smallest in the resultant array.
Thus after all elements of one array are inserted then all elements of other array are inserted directly and we get a sorted array.
Following Program illustrates the above procedure:

#include<iostream>
using namespace std;
main()
{
int a[100],b[100],c[100],n,m,k;
cout<<"Enter The no of Elements Of 1st Array ";
cin>>n;
cout<<"Enter The no of Elements Of 2nd Array ";
cin>>m;
cout<<"Enter The Elements\n";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Enter The Elements\n";
for(int j=0;j<m;j++)
cin>>b[j];
int i=0,j=0;
k=0;
while(i<=n&&j<=m)     //comparing and inserting first elements
{
if(a[i]<b[j])
{
c[k]=a[i];
k++;         //updating no of elements in resultant array
i++;
}
else if(b[j]<a[i])
{
c[k]=b[j];
j++;
k++;
}
}
k--;
if(i>n)
{for(int f=0;f<=m-j;f++)
{
c[k+f]=b[j+f];}      //inserting elements of second array
}
else if(j>m)
{
for(int f=0;f<=n-i;f++)
     {
c[k+f]=a[i+f];}     //inserting elements of first array
 }
cout<<"Sorted list is ";
for(int i=0;i<n+m;i++)
{
cout<<c[i]<<"\t";
}
}

Output: