Drill

ProblemsJava › reporting

The middle of a set of readings

mediumreportingSortingArraysMathJava

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

Java 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(List<Integer> values) {
    
}

Worked examples

CallResult
medianValue(Main.<Integer>ls(3, 1, 2))2.0
medianValue(Main.<Integer>ls(1, 2, 3, 4))2.5
medianValue(Main.<Integer>ls(7))7.0
medianValue(Main.<Integer>ls())0.0

Hint

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

Reference solution in Java
double medianValue(List<Integer> values) {
    if (values.isEmpty()) return 0.0;
    List<Integer> s = new ArrayList<>(values);
    Collections.sort(s);
    int n = s.size(), mid = n / 2;
    return n % 2 == 1 ? s.get(mid) : (s.get(mid - 1) + s.get(mid)) / 2.0;
}

The same problem in another language

More reporting problems in Java