I am a new programmer and I am trying to sort a vector of integers by their parities - put even numbers in front of odds. The order inside of the odd or even numbers themselves doesn't matter. For example, given an input [3,1,2,4], the output can be [2,4,3,1] or [4,2,1,3], etc. Below is my c++ code, sometimes I got luck that the vector gets sorted properly, sometimes it doesn't. I exported the odd and even vectors and they look correct, but when I tried to combine them together it is just messed up. Can someone please help me debug?
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
unordered_multiset<int> even;
unordered_multiset<int> odd;
vector<int> result(A.size());
for(int C:A)
{
if(C%2 == 0)
even.insert(C);
else
odd.insert(C);
}
merge(even.begin(),even.end(),odd.begin(),odd.end(),result.begin());
return result;
}
};
std::merge
works with sorted ranges. en.cppreference.com/w/cpp/algorithm/merge Your ranges are not sorted. – Retired Ninja Mar 12 '19 at 3:37std::sort
from the algorithms header with a custom comparator that sorts them the way you want them. – Cruz Jean Mar 12 '19 at 3:47std::merge
doesn't do what you think it does. – BessieTheCow Mar 12 '19 at 4:50