Write a program to find intersection of two sorted arrays in Java with output

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-14 12:52:40 Viewed : 660


Here is a Java program that finds the intersection of two sorted arrays:

java
public class IntersectionOfSortedArrays { public static void main(String[] args) { int[] array1 = {1, 3, 4, 5, 7}; int[] array2 = {2, 3, 5, 6}; int[] intersection = findIntersection(array1, array2); System.out.print("Intersection: "); for (int num : intersection) { System.out.print(num + " "); } } public static int[] findIntersection(int[] arr1, int[] arr2) { int n = arr1.length; int m = arr2.length; int i = 0, j = 0, k = 0; int[] result = new int[Math.min(n, m)]; while (i < n && j < m) { if (arr1[i] < arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { j++; } else { result[k++] = arr1[i]; i++; j++; } } return Arrays.copyOf(result, k); } }

Output:

makefile
Intersection: 3 5

In this example, the program takes two sorted arrays array1 and array2, and it uses two pointers i and j to traverse the arrays. If the elements at the current indices are equal, it adds the element to the result array and advances both pointers. If the element in array1 is smaller, it advances the pointer i, and if the element in array2 is smaller, it advances the pointer j. The result array contains the intersection of the two sorted arrays.

Search
Related Articles

Leave a Comment: