From dfe25828838a1abd0ee85d6959fb727aec5b6b9e Mon Sep 17 00:00:00 2001 From: Aakrisht69 <115407142+Aakrisht69@users.noreply.github.com> Date: Thu, 20 Oct 2022 00:33:21 +0530 Subject: [PATCH] Create Union.cpp Hacktoberfest Submission. #13 --- Cpp/Union.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Cpp/Union.cpp diff --git a/Cpp/Union.cpp b/Cpp/Union.cpp new file mode 100644 index 0000000..6883ef7 --- /dev/null +++ b/Cpp/Union.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +/* Function prints union of arr1[] and arr2[] + m is the number of elements in arr1[] + n is the number of elements in arr2[] */ +void printUnion(int arr1[], int arr2[], int m, int n) +{ + int i = 0, j = 0; + while (i < m && j < n) { + if (arr1[i] < arr2[j]) + cout << arr1[i++] << " "; + + else if (arr2[j] < arr1[i]) + cout << arr2[j++] << " "; + + else { + cout << arr2[j++] << " "; + i++; + } + } + + /* Print remaining elements of the larger array */ + while (i < m) + cout << arr1[i++] << " "; + + while (j < n) + cout << arr2[j++] << " "; +} + +/* Driver program to test above function */ +int main() +{ + int arr1[] = { 1, 2, 4, 5, 6 }; + int arr2[] = { 2, 3, 5, 7 }; + + int m = sizeof(arr1) / sizeof(arr1[0]); + int n = sizeof(arr2) / sizeof(arr2[0]); + + // Function calling + printUnion(arr1, arr2, m, n); + + return 0; +}