-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmedianSelection.cpp
84 lines (78 loc) · 1.97 KB
/
medianSelection.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//use epsilons to compare doubles
#include<bits/stdc++.h>
using namespace std;
double median(vector<double> &nums);
double pick_pivot(vector<double> &nums){
int len = nums.size();
if(len <= 5){
sort(nums.begin(), nums.end());
int x = (nums[len/2]+nums[(len-1)/2])/2;
return x;
}
int size = (len+4)/5;
vector<vector<double>> divisions(size, vector<double>());
for(int i=0; i<len; i++){
int index = i/5;
divisions[index].push_back(nums[i]);
}
vector<double> medians(size);
for(int i=0; i<size; i++){
medians[i] = pick_pivot(divisions[i]);
}
double median_of_medians = median(medians);
return median_of_medians;
}
double select(vector<double> &nums, int k){
int len = nums.size();
if(len == 1){
return nums[0];
}
double pivot = pick_pivot(nums);
vector<double> lows, pivots, highs;
for(int i=0; i<len; i++){
if(nums[i] < pivot){
lows.push_back(nums[i]);
}
else if(nums[i] == pivot){
pivots.push_back(nums[i]);
}
else{
highs.push_back(nums[i]);
}
}
if(k < lows.size()){
return select(lows, k);
}
else if(k < lows.size() + pivots.size()){
return pivots[0];
}
else{
return select(highs, k-lows.size()-pivots.size());
}
}
double median(vector<double> &nums){
int len = nums.size();
if(len%2 == 1){
return select(nums, len/2);
}
return 0.5*(select(nums, len/2)+select(nums, len/2 - 1));
}
int main(){
ifstream fin;
ofstream fout;
fin.open("inputMedian.txt");
fout.open("outputMedian.txt");
int n;
fin>>n;
vector<double> nums(n);
for(int i=0; i<n; i++){
fin>>nums[i];
}
clock_t time_req;
time_req = clock();
cout<<"Dimension: "<<n<<endl;
double med = median(nums);
cout<<"Time taken: "<<(float)time_req/CLOCKS_PER_SEC<<"s"<<endl;
fout<<med<<endl;
return 0;
}