Union of two arrays maths

Description:

Given two arrays A and B, find union between these two array. If there are repetitions, then only one occurrence of element should be printed in union. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consist of three lines. The first line of each test case contains two space separated integers N and M, where N is the size of array A and M is the size of array B. The second line of each test case contains N space separated integers denoting elements of array A. The third line of each test case contains M space separated integers denoting elements of array B. Output: Correspoding to each test case, print in a new line, the union of the two arrays in sorted order. Constraints: 1 T 30 1 N, M 1000 1 A[i], B[i] < 1000 Test Case 1 Input (stdin) 5 3 1 2 3 4 5 1 2 3 Expected Output 1 2 3 4 5 Test Case 2 Input (stdin) 6 2 85 25 1 32 54 6 85 2 Expected Output 1 2 6 25 32 54 85

Program :


import java.util.*;

public class TestClass {

public static void main(String[] args) {

int i,j,n1,n2,temp;

Scanner sc=new Scanner(System.in);

n1=sc.nextInt();

n2=sc.nextInt();

int a1[]=new int[n1];

int a2[]=new int[n2];

for(i=0;i<n1;++i)

a1[i]=sc.nextInt();

for(i=0;i<n2;++i)

a2[i]=sc.nextInt();

       for (i = 0; i < n1; i++)

        {

            for (j = i + 1; j < n1; j++)

            {

                if (a1[i] > a1[j])

                {

                    temp = a1[i];

                    a1[i] = a1[j];

                    a1[j] = temp;

                }

            }

       }

       for (i = 0; i < n2; i++)

        {

            for (j = i + 1; j < n2; j++)

            {

                if (a2[i] > a2[j])

                {

                    temp = a2[i];

                    a2[i] = a2[j];

                    a2[j] = temp;

                }

            }

       }

i=j=0;

while(i<n1&&j<n2)

{

if(a1[i]<a2[j])

{

System.out.print(a1[i]+" ");

i++;

}

else

if(a2[j]<a1[i])

{

System.out.print(a2[j]+" ");

j++;

}

else

{

System.out.print(a1[i]+" ");

i++;

j++;

}

}

if(i<n1)

while(i<n1)

{

System.out.print(a1[i]+" ");

i++;

}

if(j<n2)

while(j<n2)

{

System.out.print(a2[j]+" ");

j++;

}

}

}