Skip to content

Commit d263433

Browse files
committed
added merge_without_extra_space
1 parent 815ec44 commit d263433

File tree

1 file changed

+124
-0
lines changed

1 file changed

+124
-0
lines changed
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
//Link to the Problem:
2+
//https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays-1587115620/1
3+
4+
//Sample Test Case
5+
6+
/*
7+
8+
Input:
9+
n = 4, arr1[] = [1 3 5 7]
10+
m = 5, arr2[] = [0 2 6 8 9]
11+
12+
13+
Output:
14+
arr1[] = [0 1 2 3]
15+
arr2[] = [5 6 7 8 9]
16+
17+
18+
we start from end of first array and start of second array
19+
i.e i points to index 3 of first array and j points to index 0 of second array
20+
21+
i=3
22+
j=0
23+
24+
since 7>0, we swap both of them, now array becomes
25+
26+
arr1[] = [1 3 5 0]
27+
arr2[] = [7 2 6 8 9]
28+
29+
i=2
30+
j=1
31+
32+
since 5>2
33+
34+
arr1[] = [1 3 2 0]
35+
arr2[] = [7 5 6 8 9]
36+
37+
i=1
38+
j=2
39+
40+
3 is not greater than 6, for loop breaks and we come out of the loop
41+
42+
43+
Now we sort the arrays and get the o/p as follows:
44+
45+
arr1[] = [0 1 2 3]
46+
arr2[] = [5 6 7 8 9]
47+
48+
*/
49+
50+
#include <bits/stdc++.h>
51+
using namespace std;
52+
53+
class Solution
54+
{
55+
public:
56+
void merge(int arr1[], int arr2[], int n, int m)
57+
{
58+
59+
// Starting from last index of first array and first index of second arary
60+
int i = n - 1;
61+
int j = 0;
62+
63+
//iterating till the small array is traversed [Note that AND operator is
64+
//used]
65+
while (i >= 0 && j < m)
66+
{
67+
if (arr1[i] > arr2[j])
68+
{
69+
swap(arr1[i], arr2[j]);
70+
i--;
71+
j++;
72+
}
73+
else
74+
{
75+
break;
76+
}
77+
}
78+
79+
//Sorting both the arrays as the order in which element occured would
80+
//have changed
81+
sort(arr1, arr1 + n);
82+
sort(arr2, arr2 + m);
83+
}
84+
};
85+
86+
int main()
87+
{
88+
int t;
89+
cin >> t;
90+
while (t--)
91+
{
92+
93+
//n -> Size of first Array
94+
//m -> Size of Second Array
95+
//i -> Iterator
96+
//arr1 -> First Array
97+
//arr2 ->Second Array
98+
int n, m, i;
99+
cin >> n >> m;
100+
int arr1[n], arr2[m];
101+
for (i = 0; i < n; i++)
102+
{
103+
cin >> arr1[i];
104+
}
105+
for (i = 0; i < m; i++)
106+
{
107+
cin >> arr2[i];
108+
}
109+
110+
//Creating an instance of class
111+
Solution ob;
112+
ob.merge(arr1, arr2, n, m);
113+
for (i = 0; i < n; i++)
114+
{
115+
cout << arr1[i] << " ";
116+
}
117+
for (i = 0; i < m; i++)
118+
{
119+
cout << arr2[i] << " ";
120+
}
121+
cout << "\n";
122+
}
123+
return 0;
124+
}

0 commit comments

Comments
 (0)