The middle of the list
A dashboard shows a campaign’s typical daily spend, and “typical” is whatever lands in the middle once the days are sorted.
- An odd number of readings: the middle one, once sorted.
- An even number: the average of the two middle ones.
- An empty list has no middle: return zero.
medianOf(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
double medianOf(std::vector<int> values) {
}
Worked examples
| Call | Result |
|---|---|
medianOf(std::vector<int>{3, 1, 2}) | 2.0 |
medianOf(std::vector<int>{1, 2}) | 1.5 |
medianOf(std::vector<int>{5}) | 5.0 |
medianOf(std::vector<int>{5, 1, 4, 2}) | 3.0 |
Hint
Sort a copy, not the caller’s list, then look at the middle pair or single value.
Reference solution in C++
double medianOf(std::vector<int> values) {
std::vector<int> xs = values;
std::sort(xs.begin(), xs.end());
size_t n = xs.size();
if (n == 0) return 0.0;
size_t mid = n / 2;
return n % 2 == 1 ? xs[mid] : (xs[mid - 1] + xs[mid]) / 2.0;
}