Write your question here.
Hello everyone, I have to write a program that separates evens and odds. Like:
Input: 176809
After: 068179
I am stuck and I don't know what to do. Can someone give me another condition for this if condition: if(input[start]%2!=0 && ) and also can someone help me on the whole logic for the program? Thank you.
void separate(std::vector<int> &input)
{
int first = 0;
int last = input.size();
while (true) {
while ((first != last) && (input[first] % 2 == 0)) {
++first;
}
if (first == last--) break;
while ((first != last) && (input[last] % 2 != 0)) {
--last;
}
if (first == last) break;
std::swap(input[first++], input[last]);
}
}
Actually whole your separate function can be replaced by single line: std::partition(input.begin(), input.end(), [](int p){return p % 2 == 0;}); http://ideone.com/6NwlRK
It is already as simple as it possible. You cannot probably make it simplier (only arithmetic operations and array access are used)
We are going through array from two sides and swapping elements which are not on their places. Loop will end when beginning and end operations will intersect
Lines 6-8: we are finding first odd element
line 9: check if we finished
Lines 10-12: we are finding last even element
line 9: check if we finished
line 14: swap two elements. You can replace it with