← All resources

Merging Arrays – ISC 2001

Write a program which input natural number N and M followed by integer arrays A[] and B[], each consisting of N and M number of elements respectively. Sort the arrays A[] and B[] in descending order of magnitude. Use the sorted arrays to generate a merged array C[]. Array C[] should be generated in descending order. Assume that input arrays comprise maximum 20 elements each, with no duplicates. Common elements should be included in the merged array only once. The output format is as follows:-Write a program which input natural number N and M followed by integer arrays A[] and B[], each consisting of N and M number of elements respectively. Sort the arrays A[] and B[] in descending order of magnitude. Use the sorted arrays to generate a merged array C[]. Array C[] should be generated in descending order. Assume that input arrays comprise maximum 20 elements each, with no duplicates. Common elements should be included in the merged array only once. The output format is as follows:

import java.util.*;
public class ISC2001
{
    Scanner sc = new Scanner(System.in);
    void sort(int a[], int s)
    {
        int i, j, tmp;
        for(i=0;i<s;i++)
        {           //The function sorts any int array in descending order
            for(j=0;j<s-1-i;j++)
            {
                if(a[j]<a[j+1])
                {
                    tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = tmp;
                }
            }
        }
    }

    void input(int a[])
    {
        int i;
        for(i=0;i<a.length;i++)
        {
            a[i] = sc.nextInt();
        }
    }
    void run()
    {
        int a[], b[], c[], i, j, N, M, k=0, f;
        System.out.println("Enter the size of the two arrays: ");
        N = sc.nextInt();
        M = sc.nextInt();
        a = new int[N];
        b = new int[M];
        c = new int[M+N];
        System.out.println("Enter the values for the first array: ");
        input(a);
        System.out.println("Enter the values for the second array: ");
        input(b);
        sort(a, N);
        sort(b, M);
        for(i=0;i<N;i++)
        {       //transfering all values from first array to third array
            c[i] = a[i];
        }        
        k=N;
        for(i=0;i<M;i++)
        {
            f=1;
            for(j=0;j<N;j++)
            {
                if(b[i] == a[j])
                {
                    f = 0;
                    break;
                }
            }
            if(f==1)
            {       //transferring values from B only when they are not found in a
                c[k] = b[i];
                k++;
            }
        }
        sort(c, k);
        System.out.println("Merged Array: ");
        for(i=0;i<k;i++)
        {
            System.out.println(c[i]);
        } 
    }
    public static void main()
    {
        ISC2001 ob = new ISC2001();
        ob.run();
    }
}

OUTPUT: