Most efficient way to find the greatest of three ints

Stephano picture Stephano · Feb 10, 2010 · Viewed 16.3k times · Source

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++?

Answer

Chris H picture Chris H · Feb 10, 2010

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;