-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathmedian_of_an_array.cpp
66 lines (60 loc) · 1.34 KB
/
median_of_an_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
// C++ program for the above approach
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
// Function for calculating the median
double findMedian(vector<int> a,
int n)
{
// If size of the arr[] is even
if (n % 2 == 0) {
// Applying nth_element on n/2th index for getting sorted element
nth_element(a.begin(),
a.begin() + n / 2,
a.end());
// Applying nth_element
// on (n-1)/2 th index
nth_element(a.begin(),
a.begin() + (n - 1) / 2,
a.end());
// Find the average of value at
// index N/2 and (N-1)/2
return (double)(a[(n - 1) / 2]
+ a[n / 2])
/ 2.0;
}
// If size of the arr[] is odd
else {
// Applying nth_element on n/2 for getting sorted element
nth_element(a.begin(),
a.begin() + n / 2,
a.end());
// Value at index (N/2)th
// is the median
return (double)a[n / 2];
}
}
int main()
{
int i,n,input;
vector<int> arr;
cout << "Enter number of elements in the array" << endl;
cin >> n;
cout << "Enter the values: (space seperated)" << endl;
for (i = 0; i < n; i++)
{
cin >> input;
arr.push_back(input);
}
cout << "Array values are:" << endl;
for (i=0; i<n; i++)
{
cout << arr[i] << " ";
}
cout << endl
<< "Median = "
<< findMedian(arr, arr.size())
<< endl;
return 0;
}