Search code examples
csortinglogic

Function to return middle of 3 values?


I'm supposed to implement a function that finds the middle number from three numbers given as input. All inputs are positive integers. I seem to not be treating a special case which is causing my program to fail some tests, but with a VERY small margin. I mean 1.46 standard deviation for 8bit pixel values, so the cases I'm missing ought to be very specific and rather few in between.

As I'm understanding this problem, there's three possibilities for the numbers:

  1. They are all equal, so return either
  2. Two of them are equal, thus return the smaller one (larger one doesn't work either)
  3. They're all different, thus find the middle value

There either is a fourth case I'm not seeing or I've missed something for the above three. I can't use libraries for sorting.

int middle(int a, int b, int c)
{
    if (a == b && b == c)
    {
        return c;
    }

    if ((a < b && b < c) || (c < b && b < a))
    {
        return b;
    }

    if ((b < a && a < c) || (c < a && a < c))
    {
        return a;
    }

    if ((a < c && c < b) || (b < c && c < a))
    {
        return c;
    }

    if (a == b || b == c || a == c)
    {
        if (a == b && a < c)
        {
            return c;
        }
        else
        {
            return a;
        }

        if (b == c && b < a)
        {
            return a;
        }
        else
        {
            return b;
        }

        if (a == c && a < b)
        {
            return b;
        }
        else
        {
            return c;
        }

    }

return c; // code sometimes reaches this point; it shouldn't
}

Solution

  • This case here:

    if ((b < a && a < c) || (c < a && a < c))
    

    is incorrect. It should be:

    if ((b < a && a < c) || (c < a && a < b))
    

    Further, in the

    if (a == b || b == c || a == c)
    

    Section, you have

    if (...)
        return ...
    else
        return ...
    

    This will always return, and ignore the if statements following it.

    That said, it would be a lot easier to sort the 3 values, then return b

    if ( b < a ) {
        int t = a;
        a = b;
        b = t;
    }
    if ( c < b ) {
        int t = c;
        c = b;
        b = t;
    }
    if ( b < a ) {
        int t = a;
        a = b;
        b = t;
    }
    return b;