The middle of a set of readings
A latency report quotes the median rather than the mean, because one slow request should not move the headline number.
- Sort first — the readings arrive in whatever order they were logged.
- An odd count has a single middle value.
- An even count takes the average of the two in the middle, which may be a half.
- No readings at all gives 0.
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.
Where you start
public double MedianValue(List<int> values) {
}
Worked examples
| Call | Result |
|---|---|
MedianValue(new List<int> { 3, 1, 2 }) | 2.0d |
MedianValue(new List<int> { 1, 2, 3, 4 }) | 2.5d |
MedianValue(new List<int> { 7 }) | 7.0d |
MedianValue(new List<int> { }) | 0.0d |
Hint
After sorting, the two middles for an even count sit at n/2 - 1 and n/2.
Reference solution in C#
public double MedianValue(List<int> values) {
if (values.Count == 0) return 0.0;
var s = new List<int>(values);
s.Sort();
int n = s.Count, mid = n / 2;
return n % 2 == 1 ? s[mid] : (s[mid - 1] + s[mid]) / 2.0;
}