Number of comparisons made in median of 3 function?

Zack picture Zack · Oct 17, 2012 · Viewed 12.9k times · Source

As of right now, my functioin finds the median of 3 numbers and sorts them, but it always makes three comparisons. I'm thinking I can use a nested if statement somewhere so that sometimes my function will only make two comparisons.

int median_of_3(int list[], int p, int r)
{
    int median = (p + r) / 2;

    if(list[p] > list[r])
        exchange(list, p, r);
    if(list[p] > list[median])
        exchange(list, p, median);
    if(list[r] > list[median])
        exchange(list, r, median);

    comparisons+=3;                // 3 comparisons for each call to median_of_3

    return list[r];
}

I'm not sure I see where I can make that nested if statement.

Answer

Gyorgy Szekely picture Gyorgy Szekely · Sep 26, 2013

If you only need the median value, here's a branch-less solution based on min/max operators:

median = max(min(a,b), min(max(a,b),c));

Intel CPU's have SSE min/max vector instructions, so depending on your or your compiler's ability to vectorize, this can run extremely fast.