1
+ /* Given two sorted arrays, arr1[] and arr2[], the task is to find the
2
+ median of these sorted arrays different size. */
3
+
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ /* Function to find Median of two Sorted array of different size */
8
+ int solve ()
9
+ {
10
+ /* Input n1 = size of array 1
11
+ Input n2 = size of array 2 */
12
+ int n1,n2;
13
+ cout<<" Accept size of 1st Array : " ;
14
+ cin >> n1 ;
15
+ cout<<" Accept size of 2nd Array : " ;
16
+ cin>>n2;
17
+
18
+ int arr1[n1],arr2[n2];
19
+
20
+ /* Input values in array 1 */
21
+ cout<<" Accept the values of 1st Array : " ;
22
+ for (int i = 0 ; i < n1; ++i)
23
+ {
24
+ cin >> arr1[i];
25
+ }
26
+
27
+ /* Input values in array 2 */
28
+ cout<<" Accept the values of 2nd Array : " ;
29
+ for (int i = 0 ; i < n2; ++i)
30
+ {
31
+ cin >> arr2[i];
32
+ }
33
+
34
+ /* Create a vector */
35
+ vector<int > v;
36
+
37
+ /* Push array 1 element in vector */
38
+ for (int i = 0 ; i < n1; ++i)
39
+ {
40
+ v.push_back (arr1[i]);
41
+ }
42
+
43
+ /* Push array 2 element in vector */
44
+ for (int i = 0 ; i < n2; ++i)
45
+ {
46
+ v.push_back (arr2[i]);
47
+ }
48
+
49
+ /* Sort the given vector */
50
+ sort (v.begin (), v.end ());
51
+
52
+ /* Find medina using this formula */
53
+ int mid = v[v.size ()/2 ];
54
+
55
+ /* Return Calculated median */
56
+ return mid;
57
+ }
58
+
59
+ int main ()
60
+ {
61
+ int Median = solve ();
62
+
63
+ cout << " Median is : " << Median <<endl;
64
+ return 0 ;
65
+ }
66
+
67
+ /*
68
+ Test cases :
69
+
70
+ Input :
71
+ Accept size of 1st Array : 1
72
+ Accept size of 2nd Array : 4
73
+ Accept the values of 1st Array : 900
74
+ Accept the values of 2nd Array : 5 8 10 20
75
+
76
+ Output :
77
+ Median is : 10
78
+
79
+ Time complexity: O(nlogn)
80
+ Space Complexity: O(n)
81
+ */
0 commit comments