-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedianOf2SortedArrays.cpp
More file actions
83 lines (80 loc) · 1.58 KB
/
medianOf2SortedArrays.cpp
File metadata and controls
83 lines (80 loc) · 1.58 KB
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
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
void printArray(vector<int> arr, int n)
{
int i = 0;
cout << endl
<< "ARRAY THUS FORMED IS : ";
while (i < n)
{
cout << arr[i++] << " ";
}
}
vector<int> ans;
void mergeArray(vector<int> &nums1, vector<int> &nums2)
{
int i = 0;
int j = 0;
int n = nums1.size();
int m = nums2.size();
while (i < n && j < m)
{
if (nums1[i] <= nums2[j])
{
ans.push_back(nums1[i++]);
}
else
{
ans.push_back(nums2[j++]);
}
}
while (i < n)
{
ans.push_back(nums1[i++]);
}
while (j < m)
{
ans.push_back(nums2[j++]);
}
}
int main()
{
int n, i = 0, num;
cout << "Enter the number of Elements in Array 1 : ";
cin >> n;
vector<int> arr1;
cout << "Enter the Elements : ";
while (i < n)
{
cin >> num;
arr1.push_back(num);
i++;
}
i = 0;
cout << "Enter the number of Elements in Array 2 : ";
cin >> n;
vector<int> arr2;
cout << "Enter the Elements : ";
while (i < n)
{
cin >> num;
arr2.push_back(num);
i++;
}
printArray(arr1, arr1.size());
printArray(arr2, arr2.size());
printArray(ans, ans.size());
mergeArray(arr1, arr2);
n = ans.size();
if (n % 2 == 0)
{
int mid = n / 2;
double sol = ans[mid - 1] + ans[mid];
sol = sol / 2;
cout << endl
<< "Median is " << sol;
}
else
cout << endl
<< "median is " << ans[n / 2];
}