How do I calculate the “median of five” in C#?

后端 未结 10 2074
遇见更好的自我
遇见更好的自我 2020-12-04 22:05

The median of five is sometimes used as an exercise in algorithm design and is known to be computable using only 6 comparisons.

What is the best way

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 23:06

    Interesting how many comparisons in MSDN sample...

    public static double Median(this IEnumerable source) {
            if (source.Count() == 0)  throw new InvalidOperationException("Cannot compute median for an empty set.");
    
            var sortedList = from number in source
                             orderby number
                             select number;
    
            int itemIndex = (int)sortedList.Count() / 2;
    
            if (sortedList.Count() % 2 == 0) {
                // Even number of items.
                return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2; } else {
                // Odd number of items.
                return sortedList.ElementAt(itemIndex); }
        }
    

提交回复
热议问题