Thursday, 31 December 2020

Union of Two arrays.

Given two different sorted arrays. We need to print union of two arrays. ( Elements which are common in both the arrays)

arr1={1,3,4,5,7}

arr2={2,3,5,6}

Output: {1,2,3,4,5,6,7}

Source code:


public class Main
{
public static void main(String[] args)
{
int arr1[]={1,3,4,5,7};
int arr2[]={2,3,5,6};
union(arr1,arr2);
}
public static void union(int arr1[],int arr2[])
{
int i=0,j=0;

while(i<arr1.length&&j<arr2.length)
{
if(arr1[i]<arr2[j])
{
System.out.print(arr1[i]+" ");
i++;
}
else if(arr1[i]>arr2[j])
{
System.out.print(arr2[j]
+" ");

j++;
}
else if(arr1[i]==arr2[j])
{
System.out.print(arr1[i]
+" ");

i++;
j++;
}
}

while(i<arr1.length)
System.out.print(arr1[i++]
+" ");

while(j<arr2.length)
System.out.print(arr2[j++]
+" ");

}
}

1 comment:

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...