1+ // Problem - Merge two sorted arrays without using extra space
2+ // Since, extra space should not be used, use the input arrays itself to perform this task
3+ // For example: If the input array is,
4+ // a = [0 , 2 , 4 , 6 , 8]
5+ // b = [1 , 3 , 5 , 7]
6+ // The output arrays should be,
7+ // a = [0 , 1 , 2 , 3 , 4]
8+ // b = [5 , 6 , 7 , 8]
9+
10+ // Sample Input - 1
11+ // a = [5 , 8 , 9 , 10]
12+ // b = [1 , 2 , 100]
13+
14+ // Sample Output - 1
15+ // a = [1 , 2 , 5 , 8]
16+ // b = [9 , 10 , 100]
17+
18+ // Time Complexity: O(nlogn)
19+ // Auxiliary Space Complexity: O(1)
20+
21+ #include < iostream>
22+ #include < vector>
23+ #include < algorithm>
24+ using namespace std ;
25+
26+ // Function to merge two arrays without extra space
27+ void merge_two_arrays (vector <int > &arr1 , vector <int > &arr2) {
28+
29+ int i = arr1.size () - 1 , j = 0 ;
30+
31+ while (true ) {
32+ if (arr1[i] > arr2[j]) {
33+ swap (arr1[i] , arr2[j]);
34+ sort (arr1.begin () , arr1.end ());
35+ sort (arr2.begin () , arr2.end ());
36+ } else {
37+ break ;
38+ }
39+ }
40+
41+ }
42+
43+ int main () {
44+
45+ int n1 , n2;
46+ cout << " Enter the size of the first array : " << endl;
47+ cin >> n1;
48+
49+ cout << " Enter the size of the second array : " << endl;
50+ cin >> n2;
51+
52+ vector <int > arr1 (n1) , arr2 (n2);
53+
54+ cout << " Enter the elements of first array in sorted order : " << endl;
55+ for (int i = 0 ; i < n1; i++) {
56+ cin >> arr1[i];
57+ }
58+
59+ cout << " Enter the elements of second array in sorted order : " << endl;
60+ for (int i = 0 ; i < n2; i++) {
61+ cin >> arr2[i];
62+ }
63+
64+ merge_two_arrays (arr1 , arr2);
65+
66+ cout << " After merging : " << endl;
67+ for (int i = 0 ; i < n1; i++) {
68+ cout << arr1[i] << " " ;
69+ }
70+ for (int i = 0 ; i < n2; i++) {
71+ cout << arr2[i] << " " ;
72+ }
73+ cout << endl;
74+
75+ return 0 ;
76+ }
0 commit comments