- Related Questions & Answers
- Intersection of two arrays in Java
- Intersection of two arrays in C#
- Intersection of Two Arrays in C++
- Intersection of Two Arrays II in Python
- How to find the intersection of two arrays in java?
- How to get the intersection of two arrays in MongoDB?
- C++ program to find union and intersection of two unsorted arrays
- The intersection of two arrays in Python (Lambda expression and filter function )
- Intersection of Three Sorted Arrays in C++
- Get the intersection of two sets in Java
- Intersection of two HashSets in C#
- Intersection of Two Linked Lists in Python
- C# program to find Intersection of two lists
- Python program to find Intersection of two lists?
- Program for Point of Intersection of Two Lines in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

The intersection of the two arrays results in those elements that are contained in both of them. If an element is only in one of the arrays, it is not available in the intersection. An example of this is given as follows −

Array 1 = 1 2 5 8 9 Array 2 = 2 4 5 9 Intersection = 2 5 9

A program that demonstrates the intersection of two sorted arrays in Java is given as follows.

public class Example { public static void main(String args[]) { int arr1[] = {2, 4, 6, 8, 9}; int arr2[] = {1, 3, 4, 5, 6, 8, 9}; int m = arr1.length; int n = arr2.length; int i = 0, j = 0; System.out.print("Array 1: "); for(int k = 0; k < m; k++) { System.out.print(arr1[k] + " "); } System.out.print("\n"); System.out.print("Array 2: "); for(int k = 0; k < n; k++) { System.out.print(arr2[k] + " "); } System.out.print("\n"); System.out.print("Intersection of two arrays is: "); 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++; } } } }

The output of the above program is as follows.

Array 1: 2 4 6 8 9 Array 2: 1 3 4 5 6 8 9 Intersection of two arrays is: 4 6 8 9

Now let us understand the above program.

First, the values of the two arrays are printed. The code snippet that demonstrates this is given as follows.

System.out.print("Array 1: "); for(int k = 0; k < m; k++) { System.out.print(arr1[k] + " "); } System.out.print("\n"); System.out.print("Array 2: "); for(int k = 0; k < n; k++) { System.out.print(arr2[k] + " "); }

Then the intersection of the two arrays i.e. their common elements are displayed using a while loop. The code snippet that demonstrates this is given as follows.

System.out.print("Intersection of two arrays is: "); 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++; } }

Advertisements