Site icon

Find intersection/common elements of two sorted integer arrays in java (example)

1. Examples: intersection or common elements of two sorted arrays in java

Example #1:

Example #2:

2. Algorithm – Intersections of two sorted integer arrays in java (example)

Time complexity of algorithm is O (m+n)

3. Program – Intersection or common element of two sorted arrays in java

package org.learn.arrays;

import java.util.Arrays;

public class IntersectionSortedArrays {

	public static void main(String[] args) {

		int[] firstArray = { 1, 2, 3, 4 };
		int[] secondArray = { 3, 4, 7, 9 };

		String arr1 = Arrays.toString(firstArray);
		String arr2 = Arrays.toString(secondArray);

		System.out.printf("1. First array is : %s", arr1);
		System.out.printf("\n2. Second array is : %s", arr2);

		System.out.printf("\n3. Intersection of two sorted arrays is :");
		intersection(firstArray, secondArray);

		firstArray = new int[] { 10, 12, 16, 20 };
		secondArray = new int[] { 12, 18, 20, 22 };

		arr1 = Arrays.toString(firstArray);
		arr2 = Arrays.toString(secondArray);

		System.out.println("\n");
		System.out.printf("1. First array is : %s", arr1);
		System.out.printf("\n2. Second array is : %s", arr2);

		System.out.printf("\n3. Intersection of two sorted arrays is :");
		intersection(firstArray, secondArray);
	}

	private static void intersection(int[] arr1, int[] arr2) {
		int length1 = arr1.length;
		int length2 = arr2.length;

		int index1 = 0, index2 = 0;
		while (index1 < length1 && index2 < length2) {
			if (arr1[index1] < arr2[index2]) {
				index1++;
			} else if (arr1[index1] > arr2[index2]) {
				index2++;
			} else {
				System.out.printf(" %d", arr1[index1]);
				index1++;
				index2++;
			}
		}
	}
}

4. Output – Intersection of two sorted integer arrays in java (example)

1. First array is : [1, 2, 3, 4]
2. Second array is : [3, 4, 7, 9]
3. Intersection of two sorted arrays is : 3 4

1. First array is : [10, 12, 16, 20]
2. Second array is : [12, 18, 20, 22]
3. Intersection of two sorted arrays is : 12 20
Exit mobile version