Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Median Method to a List

Tags:

c#

list

median

I would like to override the List object in C# in order to add a Median method like Sum or Average. I already found this function:

public static decimal GetMedian(int[] array)
{
    int[] tempArray = array;
    int count = tempArray.Length;

    Array.Sort(tempArray);

    decimal medianValue = 0;

    if (count % 2 == 0)
    {
        // count is even, need to get the middle two elements, add them together, then divide by 2
        int middleElement1 = tempArray[(count / 2) - 1];
        int middleElement2 = tempArray[(count / 2)];
        medianValue = (middleElement1 + middleElement2) / 2;
    }
    else
    {
        // count is odd, simply get the middle element.
        medianValue = tempArray[(count / 2)];
    }

    return medianValue;
}

Can you tell me how to do that?

like image 325
Aladdin Gallas Avatar asked Mar 11 '11 15:03

Aladdin Gallas


People also ask

How do you find the median of a list?

The median is the number in the middle {2, 3, 11, 13, 26, 34, 47}, which in this instance is 13 since there are three numbers on either side. To find the median value in a list with an even amount of numbers, one must determine the middle pair, add them, and divide by two.

How do you find the median of a list in Python?

median() method calculates the median (middle value) of the given data set. This method also sorts the data in ascending order before calculating the median. Tip: The mathematical formula for Median is: Median = {(n + 1) / 2}th value, where n is the number of values in a set of data.

Is there a median function in Python?

In Python, the statistics. median() function is used to calculate the median value of a data set. The median() method takes in one parameter: the data list. When you call the median() method, it will order a list of values and find its middle value.


1 Answers

Use an extension method, and make a copy of the inputted array/list.

public static decimal GetMedian(this IEnumerable<int> source)
{
    // Create a copy of the input, and sort the copy
    int[] temp = source.ToArray();    
    Array.Sort(temp);

    int count = temp.Length;
    if (count == 0)
    {
        throw new InvalidOperationException("Empty collection");
    }
    else if (count % 2 == 0)
    {
        // count is even, average two middle elements
        int a = temp[count / 2 - 1];
        int b = temp[count / 2];
        return (a + b) / 2m;
    }
    else
    {
        // count is odd, return the middle element
        return temp[count / 2];
    }
}
like image 53
Greg Avatar answered Sep 21 '22 05:09

Greg