blob: 49a8a13740e8fca553f6002da25cfaa1ac625b90 [file] [log] [blame]
Matthew Barth014f07c2019-05-30 09:55:42 -05001#include <algorithm>
2#include <stdexcept>
3
4#include "utility.hpp"
5
6namespace phosphor
7{
8namespace fan
9{
10namespace control
11{
12namespace utility
13{
14
15int64_t getMedian(std::vector<int64_t>& values)
16{
17 if (values.empty())
18 {
19 throw std::out_of_range("getMedian(): Empty list of values");
20 }
21 const auto oddIt = values.begin() + values.size() / 2;
22 std::nth_element(values.begin(), oddIt, values.end());
23 auto median = *oddIt;
24 // Determine median for even number of values
25 if (values.size() % 2 == 0)
26 {
27 // Use average of middle 2 values for median
28 const auto evenIt = values.begin() + values.size() / 2 - 1;
29 std::nth_element(values.begin(), evenIt, values.end());
30 median = (median + *evenIt) / 2;
31 }
32
33 return median;
34}
35
36} // namespace utility
37} // namespace control
38} // namespace fan
39} // namespace phosphor