Site icon

Find union of two sorted integer or number arrays in java (example)

1. Examples of union of two sorted integer arrays in java

Example #1:

Fig 1: Union of two sorted array

Example #2:

2. Algorithm – find union of two sorted integer arrays in java

Time complexity of algorithm is O (m +n)

3. Program – find union of two sorted integer arrays in java (example)

package org.learn.arrays;

import java.util.Arrays;

public class UnionSortedArrays {

	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. Union of two sorted arrays is : ");
		union(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. Union of two sorted arrays is :");
		union(firstArray, secondArray);
	}

	private static void union(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]) {				
				System.out.printf(" %d", arr1[index1]);
				index1++;
				
			} else if (arr1[index1] > arr2[index2]) {				
				System.out.printf(" %d", arr2[index2]);
				index2++;
				
			} else {				
				System.out.printf(" %d", arr1[index1]);
				index1++;
				index2++;
			}
		}

		while (index1 < length1) {
			System.out.printf(" %d", arr1[index1++]);
		}

		while (index2 < length2) {
			System.out.printf(" %d", arr2[index2++]);
		}
	}
}

4. Output – find union 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. Union of two sorted arrays is :  1 2 3 4 7 9

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