How to merge two arrays without using extra space in cpp?

  array-merge, c++, merge, mergesort, sorting

This is my code,I’ve run an iterator i in the first array and swapped each element with the min_element in array 2 and then called sort on the second array.But the output isn’t sorted at all.I dont know whats wrong with this approach.

#include<bits/stdc++.h>

class Solution{
public:

void swap(int *a,int *b){
    int temp=*a;
    *a=*b;
    *b=temp;
    return;
}

void merge(int arr1[], int arr2[], int n, int m) 
{
    int i,j=0;
    while(i<n){
       if(arr1[i]<arr2[j])
       {
           i++;
       }
       else{
           swap(arr1+i,min_element(arr2,arr2+m));
           i++;
       }
    }
    sort(arr2,arr2+m);
        
}
};

For Input:

4 5 //size
1 3 5 7 //arr1
0 2 6 8 9 //arr2

your output is: 
1 3 5 7 0 2 6 8 9

Source: Windows Questions C++

LEAVE A COMMENT