Programming Examples
Cpp program to merge two sorted arrays using function
Write a cpp program to merge two sorted arrays (one in ascending and other in descending order) using function
Solution
#include<iostream>
using namespace std;
void Merge(int[],int,int[],int,int[]);
int main()
{
int arr1[50],arr2[50],rslt[50],m,n,rslt_size,i;
cout<<"Desired size of first array ";
cin>>m;
cout<<"Enter the elements in the first array (ascending order)"<<endl;
for(i=0;i<m;i++)
{
cin>>arr1[i];
}
cout<<"Desired size of second array ";
cin>>n;
cout<<"Enter the elements in the second array (descending order)"<<endl;
for(i=0;i<n;i++)
{
cin>>arr2[i];
}
rslt_size=m+n; //rslt arrays size calculated
Merge(arr1,m,arr2,n,rslt);
cout<<" Sorted Array: "<<endl;
for(i=0;i<rslt_size;i++)
{
cout<<rslt[i]<<" ";
}
return 0;
}
void Merge(int arr1[],int m,int arr2[],int n,int rslt[])
{
int p1=0,p2=n-1,a=0;
while(p1<m && p2>=0)
{
if(arr1[p1]<arr2[p2])
{
rslt[a]=arr1[p1];
p1++;
//cout<<" p1 is :"<<p1<<endl;
}
else
{
rslt[a]=arr2[p2];
p2--;
//cout<<" p2 is :"<<p2<<endl;
}
a++;
}
while(p1<m)
{
rslt[a]=arr1[p1];
p1++;
a++;
}
while(p2>=0)
{
// cout<<" P2 is : "<<p2<<" ";
rslt[a]=arr2[p2];
p2--;
a++;
}
}
Output
Desired size of first array 5
Enter the elements in the first array (ascending order)
2
4
6
8
10
Desired size of second array 6
Enter the elements in the second array (descending order)
18
15
12
9
6
3
Sorted Array:
2 3 4 6 6 8 9 10 12 15 18