Search code examples
c++median

Function to return median of 3


I am looking for the best solution to finding a median of 3. I want it to be in the least lines possible. Thank you in advance :) I've tried sth like this:

int median(int a, int b, int c)
{
    if ((a >= b && a <= c) || (a <= b && a >= c)) return a;
    if ((b >= a && b <= c) || (b <= a && b >= c)) return b;
    return c;
}

I believe this solution is okay, but maybe there is something better?


Solution

  • int median(int a, int b, int c)
    {
        return ((b > a) == (a > c)) ? a : ((a > b) == (b > c)) ? b : c;
    }
    

    https://godbolt.org/z/4G3dzPcs3

    Above code has small bug in it (prove that tests are important), here is fixed version:

    int median(int a, int b, int c)
    {
        return (b > a) == (a > c) ? a : (b > a) != (b > c) ? b : c;
    }
    

    https://godbolt.org/z/8bq38hvaj (contains testcase reviling bug in earlier code).