Question

Which the most effecient way to find a median of three integer number without using an array like the example below:

int[] median = {int a, int b,int c};
Array.Sort(median); 

int medianValue = median[1];
Was it helpful?

Solution

The fastest way I know of is to use

max(min(a, b), min(max(a, b), c))

I'm trusting that C# has optimisations for min and max taking two arguments. This will be quicker than taking if statements due to branching.

There are other tricks: you can implement min and max using XOR and < but I doubt that has any benefits on modern architectures.

OTHER TIPS

    int Median(int num1, int num2, int num3)
    {
        if ((num2 < num1 && num1 < num3) || (num2 > num1 && num1 > num3))
        {
            return num1;
        }

        if ((num1 < num2 && num2 < num3) || (num1 > num2 && num2 > num3))
        {
            return num2;
        }

        return num3;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top