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

后端 未结 10 2075
遇见更好的自我
遇见更好的自我 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

    This is pretty ugly and could use some refactoring, but it explicitly walks through all the comparisons and swaps so you can see what's going on.

    public double medianOfFive(double a, double b, double c, double d, double e){
        double median;
        // sort a and b
        if(a > b) // comparison # 1
        {
            double temp = a;
            a = b;
            b = temp;
        }
    
        // sort c and d
        if(c > d)  // comparison # 2
        {
            double temp = c;
            c = d;
            d = temp;
        }
    
        // replace the lower of a and c with e
        // because the lowest of the first four cannot be the median
        if(a < c) // comparison # 3
        {
            a = e;
            // re-sort a and b
            if(a > b) // comparison # 4
            {
                double temp = a;
                a = b;
                b = temp;
            }
        }
        else
        {
            c = e;
            // re-sort c and d
            if(c > d)  // comparison # 4
            {
                double temp = c;
                c = d;
                d = temp;
            }
        }
    
        // eliminate a or c, because the lowest
        // of the remaining four can't be the median either
        if(a < c) // comparison #5
        {
             if(b < c) // comparison #6
             {
                  median = c;
             }
             else
             {
                  median = b;
             }
        }
        else
        {
             if(d < a) // comparison #6
             {
                  median = a;
             }
             else
             {
                  median = d;
             }
        }
        return median;
    }
    

提交回复
热议问题