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

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

    private Double medianofFive(double[] input)
    {
        Double temp;
    if (input[0] > input[1])//#1 - sort First and Second
    {
        temp = input[0];
        input[0] = input[1];
        input[1] = temp;
    }
    if (input[2] > input[3])//#2 sort Third and Fourth
    {
        temp = input[2];
        input[2] = input[3];
        input[3] = temp;
    }
    
    // replace the smaller of first and third with 5th, then sort
    int smallerIndex = input[0] < input[2] ? 0 : 2;//#3
    input[smallerIndex] = input[4];
    
    //sort the new pair
    if(input[smallerIndex]>input[smallerIndex+1])//#4
    {
        temp = input[smallerIndex];
        input[smallerIndex] = input[smallerIndex+1];
        input[smallerIndex+1] = temp;
    }
    
    //compare the two smaller numbers
    // then compare the smaller of the two's partner with larger of the two
    // the smaller of THOSE two is the median
    if (input[2] > input[0])
    //#5
    {
        temp = input[2] > input[1] ? input[1] : input[2];//#6
    }
    else
    {
        temp = input[0] > input[3] ? input[3] : input[0];//#6
    }
        return temp;
    }
    

提交回复
热议问题