Most efficient way to find the greatest of three ints

前端 未结 14 1121
离开以前
离开以前 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:47

    Pseudocode:

    result = i
    if j > result:
      result = j
    if k > result:
      result = k
    return result
    
    0 讨论(0)
  • 2020-12-30 08:48

    Greatest of 3 numbers

    int greater = a>b ? (a>c? a:c) :(b>c ? b:c); 
    System.out.println(greater);
    
    0 讨论(0)
  • 2020-12-30 08:50

    I like to eliminate conditional jumps as an intellectual exercise. Whether this has any measurable effect on performance I have no idea though :)

    #include <iostream>
    #include <limits>
    
    inline int max(int a, int b)
    {
        int difference = a - b;
        int b_greater = difference >> std::numeric_limits<int>::digits;
        return a - (difference & b_greater);
    }
    
    int max(int a, int b, int c)
    {
        return max(max(a, b), c);
    }
    
    int main()
    {
        std::cout << max(1, 2, 3) << std::endl;
        std::cout << max(1, 3, 2) << std::endl;
        std::cout << max(2, 1, 3) << std::endl;
        std::cout << max(2, 3, 1) << std::endl;
        std::cout << max(3, 1, 2) << std::endl;
        std::cout << max(3, 2, 1) << std::endl;
    }
    

    This bit twiddling is just for fun, the cmov solution is probably a lot faster.

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

    The easiest way to find a maximum or minimum of 2 or more numbers in c++ is:-

    int a = 3, b = 4, c = 5;
    int maximum = max({a, b, c});
    
    int a = 3, b = 4, c = 5;
    int minimum = min({a, b, c});
    

    You can give as many variables as you want.

    Interestingly enough it is also incredibly efficient, at least as efficient as Ignacio Vazquez-Abrams'solution (https://godbolt.org/z/j1KM97):

            mov     eax, dword ptr [rsp + 8]
            mov     ecx, dword ptr [rsp + 4]
            cmp     eax, ecx
            cmovl   eax, ecx
            mov     ecx, dword ptr [rsp]
            cmp     eax, ecx
            cmovl   eax, ecx
    

    Similar with GCC, while MSVC makes a mess with a loop.

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

    Not sure if this is the most efficient or not, but it might be, and it's definitely shorter:

    int maximum = max( max(i, j), k);
    
    0 讨论(0)
  • 2020-12-30 08:53
    #include<stdio.h>
    int main()
    {
        int a,b,c,d,e;
        scanf("%d %d %d",&a,&b,&c);
        d=(a+b+abs(a-b))/2;
        e=(d+c+abs(c-d))/2;
        printf("%d is Max\n",e);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题