From ea45294211c716a820d3f6d07fa6e838a719b9a1 Mon Sep 17 00:00:00 2001 From: Akshat-706 <115639114+Akshat-706@users.noreply.github.com> Date: Fri, 25 Oct 2024 23:40:10 +0530 Subject: [PATCH] Create MergeSortedArrays.cpp This is the solution for Merging 2 sorted arrays in C++ language. --- C++/MergeSortedArrays.cpp | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 C++/MergeSortedArrays.cpp diff --git a/C++/MergeSortedArrays.cpp b/C++/MergeSortedArrays.cpp new file mode 100644 index 0000000..a66856d --- /dev/null +++ b/C++/MergeSortedArrays.cpp @@ -0,0 +1,54 @@ +#include +#include +using namespace std; + +class Solution { +public: + // Function to swap elements if the element in arr1 is greater than the element in arr2 + void swapIfGreater(vector& arr1, vector& arr2, int ind1, int ind2) { + if (arr1[ind1] > arr2[ind2]) { + swap(arr1[ind1], arr2[ind2]); //mno loop so no increment and decrement + } + } + + // Function to merge two sorted arrays + void merge(vector& arr1, int n, vector& arr2, int m) { + int len = n + m; + + // Initial gap + int gap = (len / 2) + (len % 2); + + while (gap > 0) { + int left = 0; + int right = left + gap; + + while (right < len) { + // Case 1: left in arr1 and right in arr2 + if (left < n && right >= n) { + swapIfGreater(arr1, arr2, left, right - n); + } + // Case 2: both pointers in arr2 + else if (left >= n) { + swapIfGreater(arr2, arr2, left - n, right - n); //you know why right - n + } + // Case 3: both pointers in arr1 + else { + swapIfGreater(arr1, arr1, left, right); + } + left++; + right++; + } + + // Break if iteration gap=1 is completed + if (gap == 1) break; + + // Otherwise, calculate new gap + gap = (gap / 2) + (gap % 2); + } + + // Copy remaining elements of arr2 to arr1 if any + for (int i = 0; i < m; i++) { + arr1[n + i] = arr2[i]; //arr1 taking additional elements from array 2 to store + } + } +};