find the median of a list of numbers in csharp

To find the median of a list of numbers in C#, you can follow these steps:

  1. Sort the list of numbers in ascending order.
  2. Check if the list has an odd or even number of elements. This will help determine the median value.
  3. If the list has an odd number of elements, return the middle element.
  4. If the list has an even number of elements, return the average of the two middle elements.

Here's the code:

main.cs
public static double FindMedian(List<double> numbers)
{
    numbers.Sort(); // sort the list

    int count = numbers.Count;
    if (count % 2 == 0) // even number of elements
    {
        int middle = count / 2;
        return (numbers[middle - 1] + numbers[middle]) / 2.0;
    }
    else // odd number of elements
    {
        return numbers[count / 2];
    }
}
366 chars
16 lines

This method takes a List<double> as input and returns the median value as a double. You can modify the code to work with other types of lists or arrays, as well.

related categories

gistlibby LogSnag