Find Union And Intersection of two sorted arrays

Given two sorted arrays, find their union and intersection.

For example, if the input arrays are : 

arr1[] = {1,2,3,4,5,7,9}
arr2[] = {2,4,6,8,9,10}

Then your program should print Union { 1 2 3 4 5 6 7 8 9 10 } and Intersection as { 2 4 9 }. 

For Union :

a)   Use two variables i and j for iterating, initial values i = 0, j = 0
b)   If arr1[i] < arr2[j],print arr1[i] and i++.
c)   If arr1[i] > arr2[j],print arr2[j] and j++.
d)   Ifarr1[i] == arr2[j],print any of them and i++ and j++.
e)   Print remaining elements of the array.

For Intersection : 

a)   Use two variables i and j for iterating, initial values i = 0, j = 0
b)   If arr1[i] < arr2[j], i++.
c)   If arr1[i] > arr2[j], j++.
d)   Ifarr1[i] == arr2[j],print any of them and i++ and j++.
e)   Print remaining elements of the array.

Now Let us implement the Algorithms :

public class UnionIntersectionOfTwoArrays {

  public static void main (String [] args){

	int [] array1 = {1,2,3,4,5,7,9};
	int [] array2 = {2,4,6,8,9,10};

	int arraySize1 = array1.length;
	int arraySize2 = array2.length;
	System.out.println("Printing Union:");
	printUinionOfTwoArray(array1,array2,arraySize1,arraySize2);
	
	System.out.println("\nPrinting Intersection:");
	printIntersectionOfTwoArray(array1,array2,arraySize1,arraySize2);

  }
	
  /**
   * 
   * @param array1
   * @param array2
   * @param arraySize1
   * @param arraySize2
   */
  private static void printIntersectionOfTwoArray(int arr1[],int arr2[], int arrayLength1, int arrayLength2) {
	int i = 0, j = 0;
	while (i < arrayLength1 && j < arrayLength2)
	{
	  if (arr1[i] < arr2[j])
		i++;
	  else if (arr2[j] < arr1[i])
		j++;
	  else{
		System.out.format("%d ", arr2[j]);
		i++;
		j++;
	  }
	}
  }

  /**
   * 
   * @param arr1
   * @param arr2
   * @param arrayLength1
   * @param arrayLength2
   */
  private static void  printUinionOfTwoArray(int arr1[],int arr2[], int arrayLength1, int arrayLength2){
	int i = 0, j = 0;
	while (i < arrayLength1 && j < arrayLength2)
	{
	  if (arr1[i] < arr2[j])
		System.out.format("%d ", arr1[i++]);
	  else if (arr2[j] < arr1[i])
		System.out.format("%d ", arr2[j++]);
	  else{
		System.out.format("%d ", arr2[j++]);
		i++;
	  }
	}

	/**
	 * Iterating both arrays to print remaining elements
	 */
	while(i < arrayLength1)
		System.out.format("%d ", arr1[i++]);
	while(j < arrayLength2)
		System.out.format("%d ", arr2[j++]);
  }

}

 

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself