Reputation: 2407
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];
Upvotes: 3
Views: 6217
Reputation: 255
The following is verbose, but I believe that it minimizes the number of comparisons. Note: it is possible that number of comparisons might not be the only factor in performance.
static int Median(int num1, int num2, int num3)
{
if (num1 < num2)
{
if (num2 <= num3)
return num2;
if (num1 < num3)
return num3;
return num1;
}
else
{
if (num1 <= num3)
return num1;
if (num2 < num3)
return num3;
return num2;
}
}
Upvotes: 0
Reputation: 15
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;
}
Upvotes: 0
Reputation: 234795
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.
Upvotes: 16