Skip to content

Commit db3e000

Browse files
committed
Merge branch 'jmr-stat-median'
2 parents dfc8a92 + 78220d6 commit db3e000

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

src/statistics.cc

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,13 @@ double StatisticsMedian(const std::vector<double>& v) {
4242
auto center = copy.begin() + v.size() / 2;
4343
std::nth_element(copy.begin(), center, copy.end());
4444

45-
// did we have an odd number of samples?
46-
// if yes, then center is the median
47-
// it no, then we are looking for the average between center and the value
48-
// before
45+
// Did we have an odd number of samples? If yes, then center is the median.
46+
// If not, then we are looking for the average between center and the value
47+
// before. Instead of resorting, we just look for the max value before it,
48+
// which is not necessarily the element immediately preceding `center` Since
49+
// `copy` is only partially sorted by `nth_element`.
4950
if (v.size() % 2 == 1) return *center;
50-
auto center2 = copy.begin() + v.size() / 2 - 1;
51-
std::nth_element(copy.begin(), center2, copy.end());
51+
auto center2 = std::max_element(copy.begin(), center);
5252
return (*center + *center2) / 2.0;
5353
}
5454

0 commit comments

Comments
 (0)