Program to find the union of two sorted arrays in CPP (C plus plus)
In this tutorial, we will learn about Program to find the union of two sorted arrays in CPP (C plus plus).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
#include<iostream> using namespace std; int main() { int i; int j; int l; int no; int m; int array[20]; int array1[20]; int array2[40]; cout<<"Please enter the size of first array: "; cin>>no; cout<<"Please enter the values of first array in ascending order: "<<endl; for(i=0;i<no;++i){ cin>>array[i]; } cout<<endl<<"Please enter size of second array: "; cin>>m; cout<<"Please enter the values of second array in ascending order: "<<endl; for(i=0;i<m;++i){ cin>>array1[i]; } for(i=0,j=0,l=0;i<no&&j<m;){ if(array[i]<array1[j]){ array2[l]=array[i]; i++; l++; } else if(array[i]>array1[j]){ array2[l]=array1[j]; j++; l++; } else{ array2[l]=array[i]; i++; j++; l++; } } if(i<no){ for(;i<no;++i){ array2[l]=array[i]; l++; } } else if(j<m){ for(;j<m;++j){ array2[l]=array1[j]; l++; } } cout<<endl<<"The union of two arrays is: "<<endl; for(i=0;i<l;++i){ cout<<array2[i]<<" "; } return 0; } |
Output:
