| 63 | namespace math |
| 64 | { |
| 65 | double averages::median(std::span<const double> data) |
| 66 | { |
| 67 | // The median of an odd number of elements is the value |
| 68 | // that appears in the middle position of these elements when they are sorted. |
| 69 | // The median of an even number of elements is typically |
| 70 | // defined as the mean of the two middle elements in a sorted range. |
| 71 | |
| 72 | // We cannot sort the data span itself, because it's elements are const. |
| 73 | // Therefore, we first copy the const input data to be able to sort it |
| 74 | std::vector<double> sorted; |
| 75 | |
| 76 | // Use range-based for loop to copy the input data. |
| 77 | // See Chapter 20 for built-in means of copying a data range. |
| 78 | for (auto value : data) |
| 79 | sorted.push_back(value); |
| 80 | |
| 81 | // See Chapter 20 for built-in means of (partially) sorting data |
| 82 | quicksort(sorted); |
| 83 | |
| 84 | const size_t mid = data.size() / 2; |
| 85 | return data.empty() ? std::numeric_limits<double>::quiet_NaN() // Or std::nan |
| 86 | : data.size() % 2 == 1 ? sorted[mid] |
| 87 | : (sorted[mid - 1] + sorted[mid]) / 2; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | namespace |