File indexing completed on 2024-04-06 12:01:12
0001 #ifndef CommonTools_Statistics_median_h
0002 #define CommonTools_Statistics_median_h
0003
0004 #include <vector>
0005 #include <algorithm>
0006 #include <cmath>
0007
0008
0009
0010
0011
0012
0013
0014
0015 template <class T>
0016 T median(std::vector<T> values) {
0017 switch (values.size()) {
0018 case 0:
0019
0020 case 1:
0021 return values[0];
0022 case 2:
0023 return (values[0] + values[1]) / 2.;
0024 };
0025 T ret;
0026 const int size = values.size();
0027 const int half = (int)ceil(size / 2.);
0028 partial_sort(values.begin(), values.begin() + half + 1, values.end());
0029 if (size & 1) {
0030 ret = values[half - 1];
0031 } else {
0032 ret = (values[half - 1] + values[half]) / 2.;
0033 };
0034 return ret;
0035 }
0036 #endif