Is there a more efficient way to sort two numbers?

I want dLoweru to dHigherhave lower and greater than two double values, respectively, that is, sort them if they are wrong. The most immediate answer seems to be:

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

ascending(dFoo, dBar);

But it seems like such an obvious thing, I wondered if I was using the correct terminology to find the standard procedure.

Also, how would you do this general?

+3
source share
5 answers

This is a good way to get close to it. It is as effective as you. I doubt that this particular function has a universally recognized name. This is apparently called compare-swap.

Summarizing it by type is as simple as:

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

:

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;
}

:

5, 10
3.1, 7.2
+4

" " :

template <typename T, typename StrictWeakOrdering>
void comparison_swap(T &lhs, T &rhs, StrictWeakOrdering cmp) {
    using std::swap;
    if (cmp(rhs, lhs)) {
        swap(lhs, rhs);
    }
}

template <typename T>
void comparison_swap(T &lhs, T &rhs) {
    comparison_swap(lhs, rhs, std::less<T>());
}

:

  • , , , , , .
  • - ( std::greater<T> , ). , operator< .
  • std::swap, swap, ADL, , T , .

, , .

+3

std:: sort() ?

+2

,

?

, std:: swap.

Microsoft.

template<class _Ty> inline
    void swap(_Ty& _Left, _Ty& _Right)
    {   // exchange values stored at _Left and _Right
    if (&_Left != &_Right)
        {   // different, worth swapping
        _Ty _Tmp = _Left;

        _Left = _Right;
        _Right = _Tmp;
        }
    }

, if (&_Left != &_Right) , . , .

template <class T>
inline void swap(T &left, T& right)
{
    T temp = left;
    left = right;
    right = temp;
}

10 crore. , . .

, , .. , , .

, , .

+2

, , , : ( ).

Some processors can get you the min and max of each component of the vector, one instruction each, so you can process 4 values ​​at a time - without any branches at all.

Again, this is a very special case and, most likely, is not related to what you are doing, but I wanted to do it because the “more efficient” was part of the question.

+2
source

Source: https://habr.com/ru/post/1773876/


All Articles