0
If there are two similar elements in both arrays then only one gets shifted to the third array. 

But upon printing the third array I get garbage values since the number of the same element in one array is removed while the other is shifted. In doing so, I need to reduce the length of array three as well. But what if the number of similar elements entering the code here is unknown to me. How do I avoid printing garbage value? I know there are other methods such as vector that can be also that omit garbage value but what if I need to do it using three arrays where I have to be shifting elements for both of the two elements.

void Union(int a[],int b[],int c[],int m,int n)
    {
        int i,j,k;
        i=j=k=0;
        while(i<m && j<n)
        {
            if(a[i]==b[j])
            {
                c[k++]=a[i++];
                j++;
            }
            else if(a[i]<b[j])
            {
                c[k++]=a[i++];    
            }
             else
            {
                c[k++]=b[j++];
            }
        }
            while(i<m)
            {
                c[k++]=a[i++];
            }
            while(j<n)
            {
                c[k++]=b[j++];
            }
        }
    int main()
    {
    int  a[]={1,2,5,6};
    int b[]={1,2,4,7};
    int m=sizeof(a)/sizeof(a[0]);
    int n=sizeof(b)/sizeof(b[0]);
    int c[m+n];
    Union(a,b,c,m,n);
    for(int i=0;i<m+n;i++)
    {
        cout<<c[i]<<" ";
    }
    return 0;
    }

Here I am getting output as 1 2 4 5 6 7 4717760 0 I got one garbage value and another zero. How could this be omitted?

  • Does this answer your question? [Java - Merge Two Arrays without Duplicates (No libraries allowed)](https://stackoverflow.com/questions/35329907/java-merge-two-arrays-without-duplicates-no-libraries-allowed) – Yahor Barkouski Apr 10 '22 at 11:14
  • Well, it works but not for an array whose size is greater than 10 because we will have out of bound problem due to which the last element of the first array gets copied twice on the third array. Anyway thanks for sharing it. – Bimarsh Khatri Apr 10 '22 at 13:01

0 Answers0