Merge two sorted arrays with O(1) extra space
PROBLEM :
We are given two sorted array. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1).
Example:
Input: ar1[] = {10};
ar2[] = {2, 3};
Output: ar1[] = {2}
ar2[] = {3, 10}
Input: ar1[] = {1, 5, 9, 10, 15, 20};
ar2[] = {2, 3, 8, 13};
Output: ar1[] = {1, 2, 3, 5, 8, 9}
ar2[] = {10, 13, 15, 20}
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std ;
int main(){
int t ;
cin>>t ;
while(t--)
{
int n1,n2 ;
cin>>n1>>n2 ;
int arr1[n1] ;
int arr2[n2] ;
for(int i=0;i<n1;i++)
cin>>arr1[i] ;
for(int i=0;i<n2;i++)
cin>>arr2[i] ;
int i,j,k ;
i=0 ;
while(i<n1)
{
j=0 ;
if(arr1[i]>arr2[j])
{
int temp ;
temp=arr1[i] ;
arr1[i]=arr2[j] ;
arr2[j]=temp ;
int first=arr2[j] ;
for(k=1;k<n2&&arr2[k]<first;k++)
arr2[k-1]=arr2[k] ;
arr2[k-1]=first ;
}
i++ ;
}
for(i=0;i<n1;i++)
cout<<arr1[i]<<" " ;
cout<<endl ;
for(i=0;i<n2;i++)
cout<<arr2[i]<<" " ;
cout<<endl ;
}
return 0 ;
}
--------------------------------------------------------------------------------
We are given two sorted array. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1).
Example:
Input: ar1[] = {10};
ar2[] = {2, 3};
Output: ar1[] = {2}
ar2[] = {3, 10}
Input: ar1[] = {1, 5, 9, 10, 15, 20};
ar2[] = {2, 3, 8, 13};
Output: ar1[] = {1, 2, 3, 5, 8, 9}
ar2[] = {10, 13, 15, 20}
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std ;
int main(){
int t ;
cin>>t ;
while(t--)
{
int n1,n2 ;
cin>>n1>>n2 ;
int arr1[n1] ;
int arr2[n2] ;
for(int i=0;i<n1;i++)
cin>>arr1[i] ;
for(int i=0;i<n2;i++)
cin>>arr2[i] ;
int i,j,k ;
i=0 ;
while(i<n1)
{
j=0 ;
if(arr1[i]>arr2[j])
{
int temp ;
temp=arr1[i] ;
arr1[i]=arr2[j] ;
arr2[j]=temp ;
int first=arr2[j] ;
for(k=1;k<n2&&arr2[k]<first;k++)
arr2[k-1]=arr2[k] ;
arr2[k-1]=first ;
}
i++ ;
}
for(i=0;i<n1;i++)
cout<<arr1[i]<<" " ;
cout<<endl ;
for(i=0;i<n2;i++)
cout<<arr2[i]<<" " ;
cout<<endl ;
}
return 0 ;
}
--------------------------------------------------------------------------------
Comments
Post a Comment