find the median of all elements in an array in csharp

To find the median of all elements in an array in C#, follow these steps:

  1. Sort the array in ascending or descending order.
  2. Find the middle index of the sorted array.
  3. If the array has an odd number of elements, return the element at the middle index.
  4. If the array has an even number of elements, calculate the average of the two elements at the middle indices.

Here's the code to find the median of all elements in an array in C#:

main.cs
public static double FindMedian(int[] arr)
{
    Array.Sort(arr);

    int middleIndex = arr.Length / 2;

    if (arr.Length % 2 == 0)
    {
        // array has even number of elements
        return (arr[middleIndex - 1] + arr[middleIndex]) / 2.0;
    }
    else
    {
        // array has odd number of elements
        return arr[middleIndex];
    }
}
356 chars
18 lines

You can use this method to find the median of any integer array in C#.

gistlibby LogSnag