R
R
ReD2017-05-15 11:30:20
C++ / C#
ReD, 2017-05-15 11:30:20

How to sort elements so that odd elements are on the left and even elements are on the right?

Found this solution online:

struct Comparator : public std::binary_function<int, int, bool>
{
    bool operator()(int lhs, int rhs)const
    {
        if (lhs & 1  &&  rhs & 1)
            return lhs < rhs;
        return lhs & 1;
    }
};

std::sort(vec.begin(), vec.end(), Comparator());

But I didn’t understand the logic of triggering the condition: Please explain how the expression works:
if (lhs & 1 && rhs & 1)
(lhs & 1 && rhs & 1)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-05-15
@trinitr0

Read about bit operations. In short, the last bit of an odd number in binary representation is always 1, for example, 3 is 11, 5 is 101, and so on.

M
Mace_UA, 2017-05-25
@Mace_UA

2017 You don't need any std::binary_functionother obsolete bullshit. Yes, and you can use a lambda if this comparator is needed only in one place in the code.
Judging by the description of the task, you do not need to sort the array - you need to make a partition.
Use standard algorithms std::partition(if the relative order of even and odd elements among themselves is not important) or std::stable_partition(if you need to preserve the original order).
Example:

std::stable_partition(vec.begin(), vec.end(), [](int x) { return x % 2 == 1; });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question