Java program to find Union and Intersection of two sorted arrays :
In this tutorial, we will find the union and intersection of two sorted array elements. Let’s find out the union first :
Union of two sorted arrays using Java :
-
Scan both arrays simultaneously
-
Compare element of both of the array and print the smaller value.
-
Increment the counter of the array with the smaller value.
-
After smaller array is completed. Print out the remaining elements of the larger array.
Source code :
public class Main {
public static void main(String[] args) {
int[] firstArr = {1, 2, 3, 4, 5, 6};
int[] secondArr = {4, 9, 13, 15, 16, 17};
findUnion(firstArr, secondArr);
}
private static void findUnion(int[] firstArr, int[] secondArr) {
int i = 0;
int j = 0;
while (i < firstArr.length && j < secondArr.length) {
if (firstArr[i] < secondArr[j]) {
System.out.print(firstArr[i] + " ");
i++;
} else if (secondArr[j] < firstArr[i]) {
System.out.print(secondArr[j] + " ");
j++;
} else {
System.out.print(firstArr[i] + " ");
i++;
j++;
}
}
while (i < firstArr.length) {
System.out.print(firstArr[i] + " ");
i++;
}
while (j < secondArr.length) {
System.out.print(secondArr[j] + " ");
j++;
}
}
}
Intersection of two sorted arrays using Java :
-
Scan both arrays simultaneously
-
Compare element of both of the arrays.
-
If both of the values are the same, print it.
-
Else, increment the counter of the array with smaller element.
Source Code :
public class Main {
public static void main(String[] args) {
int[] firstArr = {1, 2, 3, 4, 5, 6};
int[] secondArr = {4, 9, 13, 15, 16, 17};
findIntersection(firstArr, secondArr);
}
private static void findIntersection(int[] firstArr, int[] secondArr) {
int i = 0;
int j = 0;
while (i < firstArr.length && j < secondArr.length) {
if (firstArr[i] < secondArr[j]) {
i++;
} else if (firstArr[i] > secondArr[j]) {
j++;
} else {
System.out.print(firstArr[i] + " ");
i++;
j++;
}
}
}
}
Similar tutorials :
- Java Linear Search : search one element in an array
- Java program to find union and intersection of two arrays
- Java program to convert string to byte array and byte array to string
- Java program to find out the top 3 numbers in an array
- Java program to merge values of two integer arrays
- Java example program to left shift an array