From 85822608bb4d01fef6dbca7e2841027df44f00c7 Mon Sep 17 00:00:00 2001 From: 12345rams <132057037+12345rams@users.noreply.github.com> Date: Sat, 21 Oct 2023 20:33:03 +0530 Subject: [PATCH] Create UnionOfTwoArrays.java This Java program finds and displays the union of two sorted arrays. The union includes unique elements that are present in both arrays, and distinct elements from both arrays. Users provide input for the arrays' sizes and elements, and the program uses a Set data structure to efficiently calculate and show the union. This code is helpful for various applications involving set operations and data processing. --- JAVA/UnionOfTwoArrays.java | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 JAVA/UnionOfTwoArrays.java diff --git a/JAVA/UnionOfTwoArrays.java b/JAVA/UnionOfTwoArrays.java new file mode 100644 index 0000000..a38a2c1 --- /dev/null +++ b/JAVA/UnionOfTwoArrays.java @@ -0,0 +1,63 @@ +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +public class ArrayUnion { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the size of the first array (n): "); + int n = scanner.nextInt(); + int[] arr1 = new int[n]; + System.out.print("Enter the elements of the first array: "); + for (int i = 0; i < n; i++) { + arr1[i] = scanner.nextInt(); + } + + System.out.print("Enter the size of the second array (m): "); + int m = scanner.nextInt(); + int[] arr2 = new int[m]; + System.out.print("Enter the elements of the second array: "); + for (int i = 0; i < m; i++) { + arr2[i] = scanner.nextInt(); + } + + findUnion(arr1, arr2); + } + + public static void findUnion(int[] arr1, int[] arr2) { + Set union = new HashSet<>(); + + int i = 0; + int j = 0; + + while (i < arr1.length && j < arr2.length) { + if (arr1[i] < arr2[j]) { + union.add(arr1[i]); + i++; + } else if (arr1[i] > arr2[j]) { + union.add(arr2[j]); + j++; + } else { + union.add(arr1[i]); + i++; + j++; + } + } + + while (i < arr1.length) { + union.add(arr1[i]); + i++; + } + + while (j < arr2.length) { + union.add(arr2[j]); + j++; + } + + System.out.print("Union of the two arrays: "); + for (int num : union) { + System.out.print(num + " "); + } + } +}