Java Program to Find Union of two Arrays

For example we have two sorted arrays a1[]={2,3,5,11} and a2[]={4,7,9} then union of a1 and a2 will be {2,3,4,5,7,9,11}. A Java program for finding union of two arrays is given below.

Also Read: Java Program to Find Smallest and Largest Element in an Array

Java Program to Find Union of two Arrays

import java.util.Scanner; //import Scanner class in our program


class demo
{
public static void main(String…s)
{
int i,j,n1,n2;
Scanner sc=new Scanner(System.in); //used to read from keyboard


System.out.print(“Enter number of elements of first array:”);
n1=sc.nextInt();
System.out.print(“Enter number of elements of second array:”);
n2=sc.nextInt();


int a1[]=new int[n1];
int a2[]=new int[n2];


System.out.print(“nEnter elements of first array in ascending order:”);
for(i=0;i<n1;++i)
a1[i]=sc.nextInt();


System.out.print(“nEnter elements of second array in ascending order:”);
for(i=0;i<n2;++i)
a2[i]=sc.nextInt();




i=j=0;
System.out.print(“nUnion of Arrays: “);
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++;
}

}
}

Java Program to Find Union of two Arrays

One thought on “Java Program to Find Union of two Arrays

  1. Дмитрий Згурский

    class Program
    {
    static void Main(string[] args)
    {
    int[] arrFirst = {2, 3, 5, 11};
    int[] arrSecond = {4, 7, 9};
    MyClass myClass = new MyClass();
    myClass.UnionTwoArrays(arrFirst, arrSecond);
    Console.ReadLine();
    }
    }

    class MyClass
    {
    private List doneList = new List();
    public void UnionTwoArrays(int[] first, int[] second)
    {
    foreach (int i in first)
    {
    doneList.Add(i);
    }
    foreach (int i in second)
    {
    doneList.Add(i);
    }
    doneList.Sort();
    foreach (int i in doneList)
    {
    Console.WriteLine(i);
    }
    }
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *