Search code examples
c#.netalgorithmmedian

Calculate median in c#


I need to write function that will accept array of decimals and it will find the median.

Is there a function in the .net Math library?


Solution

  • Is there a function in the .net Math library?

    No.

    It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n) while its possible to solve this problem in O(n) time. You want to look at selection algorithms to get such an algorithm.