Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way to sort two numbers?

Tags:

c++

I want dLower and dHigher to have the lower and higher of two double values, respectively - i.e. to sort them if they are the wrong way around. The most immediate answer, it seems is:

void ascending(double& dFirst, double& dSecond)
{
    if(dFirst > dSecond)
        swap(dFirst,dSecond);
}

ascending(dFoo, dBar);

But it seems like such an obvious thing to do I wondered if I'm just not using the right terminology to find a standard routine.

Also, how would you make that generic?

like image 789
Phil H Avatar asked Nov 09 '10 15:11

Phil H


1 Answers

This is a good way of approaching it. It is as efficient as you are going to get. I doubt that this specific function has a generally recognized name. This is apparently called comparison-swap.

Generalizing it on type is as easy as:

template <typename T>
void ascending(T& dFirst, T& dSecond)
{
    if (dFirst > dSecond)
        std::swap(dFirst, dSecond);
}

Corroborating this function:

int main() {
    int a=10, b=5;
    ascending(a, b);
    std::cout << a << ", " << b << std::endl;

    double c=7.2, d=3.1;
    ascending(c, d);
    std::cout << c << ", " << d << std::endl;

    return 0;
}

This prints:

5, 10
3.1, 7.2
like image 109
Magnus Hoff Avatar answered Oct 20 '22 01:10

Magnus Hoff