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

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

    This is basically just factoring out the swapping and sorting code from your C++ example:

    private static void Swap(ref double a, ref double b) {
        double t = a;
        a = b;
        b = t;
    }
    
    private static void Sort(ref double a, ref double b) {
        if (a > b) {
            double t = a;
            a = b;
            b = t;
        }
    }
    
    private static double MedianOfFive(double a, double b, double c, double d, double e){
        // makes a < b and c < d
        Sort(ref a, ref b);
        Sort(ref c, ref d);
    
        // eleminate the lowest
        if (c < a) {
            Swap(ref b, ref d);
            c = a;
        }
    
        // gets e in
        a = e;
    
        // makes a < b
        Sort(ref a, ref b);
    
        // eliminate another lowest
        // remaing: a,b,d
        if (a < c) {
            Swap(ref b, ref d);
            a = c;
        }
    
        return Math.Min(d, a);
    }
    

提交回复
热议问题