-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_Without_Extra_Space.cpp
72 lines (51 loc) · 1.18 KB
/
Merge_Without_Extra_Space.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// Function to merge two input arrays
// arr1[], arr2[]: input arrays
// n, m: size of arr1[] and arr2[] respectively
void merge(int arr1[], int arr2[], int n, int m)
{
vector<int> arr(n+m);
int i = 0,j = 0,k = 0;
while(i < n && j < m)
{
if(arr1[i] < arr2[j])
arr[k++] = arr1[i++];
else
arr[k++] = arr2[j++];
}
while(i < n)
arr[k++] = arr1[i++];
while(j < m)
arr[k++] = arr2[j++];
for(i = 0; i < n; ++i)
arr1[i] = arr[i];
for(j = n; j < m+n; ++j)
arr2[j-n] = arr[j];
}
// { Driver Code Starts.
int main()
{
int T;
cin >> T;
while(T--){
int n, m;
cin >> n >> m;
int arr1[n], arr2[m];
for(int i = 0;i<n;i++){
cin >> arr1[i];
}
for(int i = 0;i<m;i++){
cin >> arr2[i];
}
merge(arr1, arr2, n, m);
for (int i = 0; i < n; i++)
printf("%d ", arr1[i]);
for (int i = 0; i < m; i++)
printf("%d ", arr2[i]);
cout<<endl;
}
return 0;
}
// } Driver Code Ends