Most efficient way to find the greatest of three ints

前端 未结 14 1122
离开以前
离开以前 2020-12-30 07:58

Below is my pseudo code.

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


        
相关标签:
14条回答
  • 2020-12-30 08:54

    Your current method: http://ideone.com/JZEqZTlj (0.40s)

    Chris's solution:

    int ret = max(i,j);
    ret = max(ret, k);
    return ret;
    

    http://ideone.com/hlnl7QZX (0.39s)

    Solution by Ignacio Vazquez-Abrams:

    result = i;
    if (j > result)
      result = j;
    if (k > result)
      result = k;
    return result;
    

    http://ideone.com/JKbtkgXi (0.40s)

    And Charles Bretana's:

    return i > j? (i > k? i: k): (j > k? j: k);
    

    http://ideone.com/kyl0SpUZ (0.40s)

    Of those tests, all the solutions take within 3% the amount of time to execute as the others. The code you are trying to optimize is extremely short as it is. Even if you're able to squeeze 1 instruction out of it, it's not likely to make a huge difference across the entirety of your program (modern compilers might catch that small optimization). Spend your time elsewhere.

    EDIT: Updated the tests, turns out it was still optimizing parts of it out before. Hopefully it's not anymore.

    0 讨论(0)
  • 2020-12-30 08:55

    How about

    return i > j? (i > k? i: k): (j > k? j: k);
    

    two comparisons, no use of transient temporary stack variables...

    0 讨论(0)
提交回复
热议问题