MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / median

Method median

Examples/NoModules/Chapter 11/Ex11_07/math.cpp:65–88  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

63namespace 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
91namespace

Callers

nothing calls this directly

Calls 4

quicksortFunction · 0.70
push_backMethod · 0.45
sizeMethod · 0.45
emptyMethod · 0.45

Tested by

no test coverage detected