Answer the question
In order to leave comments, you need to log in
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());
if (lhs & 1 && rhs & 1)
(lhs & 1 && rhs & 1)
Answer the question
In order to leave comments, you need to log in
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.
2017 You don't need any std::binary_function
other 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 questionAsk a Question
731 491 924 answers to any question