Program for Merge an array of size n into another array of size m
Source Code:
#include <iostream>
#include <iomanip>
using namespace std;
void display(int arr[],int x){
for (int i=0;i<x;i++){
cout<<setw(5)<<arr[i];
}
cout<<endl;
cout<<"---------------------------------------------------"<<endl;
}
void merge(int arr1[],int a,int arr2[],int b){
int result_arr[a+b];
int i=0,j=0,k=0;
while(i<a && j<b){
if (arr1[i]<arr2[j]){
result_arr[k]=arr1[i];
k+=1;i+=1;
}
else{
result_arr[k]=arr2[j];
k+=1;j+=1;
}
}
while (i<a){
result_arr[k]=arr1[i];
k+=1;i+=1;
}
while (j<b){
result_arr[k]=arr2[j];
k+=1;j+=1;
}
for (int i=0;i<k;i++){
cout<<setw(5)<<result_arr[i];
}
}
int main(){
int a,b;
cout<<"Enter the number of elements in the first array: ";
cin>>a;
cout<<"Enter the number of elements in the second array: ";
cin>>b;
int arr1[a],arr2[b];
cout<<"---------------------------------------------------"<<endl;
for (int i=0;i<a;i++){
cout<<"Enter the elements of the array: ";
cin>>arr1[i];
}
cout<<"---------------------------------------------------"<<endl;
for (int i=0;i<b;i++){
cout<<"Enter the elements of the array: ";
cin>>arr2[i];
}
cout<<"The first array is: "<<endl;
display(arr1,a);
cout<<"The second array is: "<<endl;
display(arr2,b);
cout<<"The combined array is: "<<endl;
merge(arr1,a,arr2,b);
return 0;
}
0 Comments
Post a Comment