merge two sorted arrays without using extra space ( GAP Method) [closed]

  array-merge, arrays, c++
#include<bits/stdc++.h>
using namespace std;

class Solution{
public:
    void merge(int arr1[], int arr2[], int n, int m) {
        // code here
       int gap,cnt=0;
       gap=(m+n)%2+(m+n)/2;
       while(gap>=1 && cnt<=1)
       {  
           for(int i=0,j=gap-1;j<m+n;j++,i++ )
           {    
               
               if(i>=n )
                {    
                  if(arr2[j-n]<arr2[i-n])
                  swap(arr2[j-n],arr2[i-n]);
                }
    
               else{
                    if(j<n)
                    {
                        if(arr1[j]<arr1[i])
                        swap(arr1[j],arr1[i]);
                    }
                     else
                    {
                        if(arr2[j-n]<arr1[i])
                        swap(arr2[j-n],arr1[i]);
                   }
               }
                    
             }
           gap=(gap/2)+(gap%2);
           if(gap==1)
           cnt++;
       }
       
    }
};
int main()
{
    int a1[] = { 10, 27, 38, 43, 82 };
    int a2[] = { 3, 9 };
    int n = sizeof(a1) / sizeof(int);
    int m = sizeof(a2) / sizeof(int);

    // Function Call
Solution ob;
    ob.merge(a1, a2, n, m);

    printf("First Array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", a1[i]);

    printf("nSecond Array: ");
    for (int i = 0; i < m; i++)
        printf("%d ", a2[i]);
    printf("n");
    return 0;
}

This is my code. It is giving wrong answer on some test cases though i have tried to cover everything and many test cases have been passed. Kindly help.
Test Case:

20 10
1 1 1 2 3 5 7 7 7 9 9 13 13 14 14 17 17 19 20 20
3 5 7 9 10 12 13 14 20 20

Link to question and platform used: https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays5135/1#
Kindly check the test case there you would see some adjacent elements have not swapped though i covered it in my case. Kindly help and modify this code to meet the requirements instead of giving a new solution. Thank you.

PS: I have used cnt variable so that when gap equals 1 then it should execute only 1 time i.e. swap adjacent if required.

Source: Windows Questions C++

LEAVE A COMMENT