From e8246c86d4dd3028f417430a963e869d34a53cb6 Mon Sep 17 00:00:00 2001 From: Abhishek Kushwah <63289147+abhishekkushwah827@users.noreply.github.com> Date: Sat, 2 Oct 2021 11:20:08 +0530 Subject: [PATCH] Create Find Union of two sorted Array in JAVA --- Find Union of two sorted Array in JAVA | 40 ++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Find Union of two sorted Array in JAVA diff --git a/Find Union of two sorted Array in JAVA b/Find Union of two sorted Array in JAVA new file mode 100644 index 0000000..cfaf2f2 --- /dev/null +++ b/Find Union of two sorted Array in JAVA @@ -0,0 +1,40 @@ +// Java program to find union of +// two sorted arrays + +class FindUnion { + /* Function prints union of arr1[] and arr2[] + m is the number of elements in arr1[] + n is the number of elements in arr2[] */ + static int printUnion(int arr1[], int arr2[], int m, int n) + { + int i = 0, j = 0; + while (i < m && j < n) { + if (arr1[i] < arr2[j]) + System.out.print(arr1[i++] + " "); + else if (arr2[j] < arr1[i]) + System.out.print(arr2[j++] + " "); + else { + System.out.print(arr2[j++] + " "); + i++; + } + } + + /* Print remaining elements of + the larger array */ + while (i < m) + System.out.print(arr1[i++] + " "); + while (j < n) + System.out.print(arr2[j++] + " "); + + return 0; + } + + public static void main(String args[]) + { + int arr1[] = { 1, 2, 4, 5, 6 }; + int arr2[] = { 2, 3, 5, 7 }; + int m = arr1.length; + int n = arr2.length; + printUnion(arr1, arr2, m, n); + } +}