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++]+" ");
}
}
Nice Program. For more programs for the blog, you can refer C programs
ReplyDelete