-
Notifications
You must be signed in to change notification settings - Fork 91
/
merge_array.cpp
70 lines (60 loc) · 1.32 KB
/
merge_array.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
//Merge two sorted arrays without using extra space
/*
n: size of 1st array
m: size of 2nd array
eg.
Input:
n = 4, arr1[] = [1 3 5 7]
m = 5, arr2[] = [0 2 6 8 9]
Output:
arr1[] = [0 1 2 3]
arr2[] = [5 6 7 8 9]
*/
#include <bits/stdc++.h>
using namespace std;
//Function to merge the arrays.
void merge(long long arr1[], long long arr2[], int n, int m) {
int i=0, j=0, k=n-1;
while(i<=k && j<m){
if(arr1[i]<arr2[j])
i++;
else{
swap(arr2[j], arr1[k]);
j++;k--;
}
}
sort(arr1, arr1+n);
sort(arr2, arr2+m);
}
int main()
{
//input two arrays (sorted)
cout<<"Enter size of array1\n";
int n, m;
cin >> n;
cout<<"\nEnter size of array2\n";
cin >>m;
long long arr1[n], arr2[m];
cout<<"\nEnter "<<n<<" elements of array1\n";
for(int i = 0;i<n;i++){
cin >> arr1[i];
}
sort(arr1,arr1+n);
cout<<"\nEnter "<<m<<" elements of array2\n";
for(int i = 0;i<m;i++){
cin >> arr2[i];
}
sort(arr2,arr2+m);
//call function
merge(arr1, arr2, n, m);
//output
cout<<"\nAfter Merging:\n";
cout<<"\narray1 is-\n";
for (int i = 0; i < n; i++)
cout<<arr1[i]<<" ";
cout<<"\narray2 is-\n";
for (int i = 0; i < m; i++)
cout<<arr2[i]<<" ";
cout<<endl;
return 0;
}