Drill

ProblemsC# › patterns

The middle of the list

mediumpatternsSortingArraysMathC#

A dashboard shows a campaign’s typical daily spend, and “typical” is whatever lands in the middle once the days are sorted.

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.

Solve it in Python →

Where you start

public double MedianOf(List<int> values) {
    
}

Worked examples

CallResult
MedianOf(new List<int> { 3, 1, 2 })2.0d
MedianOf(new List<int> { 1, 2 })1.5d
MedianOf(new List<int> { 5 })5.0d
MedianOf(new List<int> { 5, 1, 4, 2 })3.0d

Hint

Sort a copy, not the caller’s list, then look at the middle pair or single value.

Reference solution in C#
public double MedianOf(List<int> values) {
    var xs = values.OrderBy(v => v).ToList();
    int n = xs.Count;
    if (n == 0) return 0.0;
    int mid = n / 2;
    return n % 2 == 1 ? xs[mid] : (xs[mid - 1] + xs[mid]) / 2.0;
}

The same problem in another language

More patterns problems in C#