-
Notifications
You must be signed in to change notification settings - Fork 69
/
Median of Two Sorted Arrays #105.txt
83 lines (66 loc) Β· 1.46 KB
/
Median of Two Sorted Arrays #105.txt
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;
float MergeSortedArrays(int nums1[], int m, int nums2[], int n, int nums3[], int s)
{
int i = 0, j = 0, k = 0;
while(i<m && j<n)
{
if(nums1[i] < nums2[j])
{
nums3[k] = nums1[i];
i++;
k++;
}
else
{
nums3[k] = nums2[j];
j++;
k++;
}
}
while(i<m)
{
nums3[k] = nums1[i];
i++;
k++;
}
while(j<n)
{
nums3[k] = nums2[j];
j++;
k++;
}
if(s % 2 != 0)
{
return (float)(nums3[s/2]);
}
else
{
return (float)(nums3[s/2] + nums3[(s/2)-1])/2;
}
}
int main()
{
int m, n;
cout<<"Enter Size of 1st Array : "<<endl;
cin>>m;
cout<<"\nEnter Size of 2nd Array : "<<endl;
cin>>n;
int nums1[m], nums2[n];
cout<<"\nEnter "<<m<<" elements of 1st Array in Sorted Order\n"<<endl;
for(int i=0; i<m; i++)
{
cout<<"nums1["<<i<<"] : ";
cin>>nums1[i];
}
cout<<"\nEnter "<<n<<" elements of 2nd Array in Sorted Order\n"<<endl;
for(int i=0; i<n; i++)
{
cout<<"nums2["<<i<<"] : ";
cin>>nums2[i];
}
int s = m+n;
int nums3[s];
cout<<"\nThe Median of two Sorted Arrays is : "<< MergeSortedArrays(nums1, m, nums2, n, nums3, s)<<"\n";
return 0;
}