Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to find the greatest of three ints

Below is my pseudo code.

function highest(i, j, k)
{
  if(i > j && i > k)
  {
    return i;
  }
  else if (j > k)
  {
    return j;
  }
  else
  {
    return k;
  }
}

I think that works, but is that the most efficient way in C++?

like image 241
Stephano Avatar asked Feb 09 '10 23:02

Stephano


People also ask

How to find max between three numbers?

First, the three numbers are defined. If num1 is greater than num2 and num3, then it is the maximum number. If num2 is greater than num1 and num3, it is the maximum number.

Is Max function available in C?

Say max() function is used to find maximum between two numbers. Second, we need to find maximum between two numbers. Hence, the function must accept two parameters of int type say, max(int num1, int num2). Finally, the function should return maximum among given two numbers.


1 Answers

To find the greatest you need to look at exactly 3 ints, no more no less. You're looking at 6 with 3 compares. You should be able to do it in 3 and 2 compares.

int ret = max(i,j);
ret = max(ret, k);
return ret;
like image 88
Chris H Avatar answered Oct 29 '22 18:10

Chris H