Is this homework? If not, use std::stable_partition()
:
struct IsEven {
template<class T>
bool operator()(const T& v) const { return v % 2 == 0; }
};
int* arr = {1,2,3,4,5,6,7,8};
int* mid = std::stable_partition(arr, arr+8, IsEven());
If it is a homework, then your instructor probably expects you to write the algorithm. If you don't have to maintain the ordering as in the input sequence then you can do it rather efficiently:
- Find the first element that doesn't satisfy the predicate (i.e., is odd).
- Find that last element that does satisfy the predicate (i.e., is even)
- swap the two elements.
- Repeat, starting from the positions you just found, until the two positions meet.
- The point where the two positions meet is the middle of the partition, where even numbers stop and odd numbers begin.
This is roughly how std::partition()
works. If you do have to maintain the relative ordering in the input array then you can still do it in-place, but it will be faster if you use a temporary buffer. Copy the elements that don't match the predicate into that buffer, and squeeze in place those that do. Finally bring back in the elements that don't match, at the end of the array, in order.