In: Computer Science
Please use Java language to write two efficient functions:
Write an efficient function that compute the intersections of two sorted arrays of integers
Write an efficient function that compute the intersection of two arrays of integers (not
necessary sorted).
CODE
import java.util.HashSet;
public class Main
{
public static void findIntersectionForSortedArrays(int
arr1[], int arr2[])
{
int m = arr1.length;
int n = arr2.length;
int i = 0, j = 0;
while (i < m && j <
n)
{
if (arr1[i] <
arr2[j])
i++;
else if (arr2[j]
< arr1[i])
j++;
else
{
System.out.print(arr2[j++]+" ");
i++;
}
}
}
public static void
findIntersectionForUnsortedArrays(int arr1[], int arr2[])
{
HashSet<Integer>
hs = new HashSet<>();
for (int i = 0; i <
arr1.length; i++)
hs.add(arr1[i]);
for (int i = 0; i <
arr2.length; i++)
if (hs.contains(arr2[i]))
System.out.print(arr2[i] + " ");
}
public static void main(String args[])
{
int arr1[] = {1, 3, 4, 6, 8, 10,
11};
int arr2[] = {3, 4, 7, 8};
findIntersectionForSortedArrays(arr1, arr2);
System.out.println();
int arr3[] = {1, 9, 5, 4, 8,
6};
int arr4[] = {7, 8, 9,
1, 17, 20, 4};
findIntersectionForUnsortedArrays(arr3, arr4);
}
}