Drill

ProblemsC++ › reporting

The middle of a set of readings

mediumreportingSortingArraysMathC++

A latency report quotes the median rather than the mean, because one slow request should not move the headline number.

medianValue(values: list<int>) → float

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

double medianValue(std::vector<int> values) {
    
}

Worked examples

CallResult
medianValue(std::vector<int>{3, 1, 2})2.0
medianValue(std::vector<int>{1, 2, 3, 4})2.5
medianValue(std::vector<int>{7})7.0
medianValue(std::vector<int>{})0.0

Hint

After sorting, the two middles for an even count sit at n/2 - 1 and n/2.

Reference solution in C++
double medianValue(std::vector<int> values) {
    if (values.empty()) return 0.0;
    std::vector<int> s = values;
    std::sort(s.begin(), s.end());
    int n = (int) s.size(), mid = n / 2;
    if (n % 2 == 1) return s[mid];
    return (s[mid - 1] + s[mid]) / 2.0;
}

The same problem in another language

More reporting problems in C++