Skip to content

Instantly share code, notes, and snippets.

@itrare
Last active July 5, 2020 17:33
Show Gist options
  • Save itrare/7602c8dc845ec8dd41fc42b0a5d1680d to your computer and use it in GitHub Desktop.
Save itrare/7602c8dc845ec8dd41fc42b0a5d1680d to your computer and use it in GitHub Desktop.
This program merge two sorted arrays using recursion in c++ programming language.
//program to merge two array using recursive function
#include "iostream"
#include "conio.h"
using namespace std;
void merge_r(int a1[],int a2[],int c[],int s1,int s2,int i=0,int j=0,int k=0){
if(i<s1 && j<s2){
if(a1[i]>a2[j]){
c[k++]=a2[j++];
}else{
c[k++]=a1[i++];
}
merge_r(a1,a2,c,s1,s2,i,j,k);
}
else{
if(i<s1){
c[k++]=a1[i++];
merge_r(a1,a2,c,s1,s2,i,j,k);
}
if(j<s2){
c[k++]=a2[j++];
merge_r(a1,a2,c,s1,s2,i,j,k);
}
}
}
int main(){
int *a1= new int,*a2= new int,s1,s2;
int *c =new int;
cout<<"Size of the first array : ",cin>>s1;
cout<<"Size of the Second array : ",cin>>s2;
for (int i=0;i<s1;i++){
cin>>a1[i];
}
for (int i=0;i<s2;i++){
cin>>a2[i];
}
merge_r(a1,a2,c,s1,s2);
for(int i=0;i<s1+s2;i++){
cout<<c[i]<<" ";
}
getch();
delete []a1;
delete []a2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment