blob: 8c8dadd693063557136c5d61861fefc108d94bd5 [file] [log] [blame]
Matthew Barth3e1bb272020-05-26 11:09:21 -05001#include "utility.hpp"
2
Matthew Barth014f07c2019-05-30 09:55:42 -05003#include <algorithm>
4#include <stdexcept>
5
Matthew Barth014f07c2019-05-30 09:55:42 -05006namespace 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