Matthew Barth | 3e1bb27 | 2020-05-26 11:09:21 -0500 | [diff] [blame] | 1 | #include "utility.hpp" |
| 2 | |
Matthew Barth | 014f07c | 2019-05-30 09:55:42 -0500 | [diff] [blame] | 3 | #include <algorithm> |
| 4 | #include <stdexcept> |
| 5 | |
Matthew Barth | 014f07c | 2019-05-30 09:55:42 -0500 | [diff] [blame] | 6 | namespace phosphor |
| 7 | { |
| 8 | namespace fan |
| 9 | { |
| 10 | namespace control |
| 11 | { |
| 12 | namespace utility |
| 13 | { |
| 14 | |
| 15 | int64_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 |