Adjust the order of the array so that in front of the even-odd
topic
Enter an array of integers, to realize a function to adjust the order of the numbers in the array.
All odd positioned such that the first half of the array, all even located in the second half of the array.
Sample
Input: [1,2,3,4,5]
Output: [1,3,5,2,4]
answer
Double pointer arithmetic, the head pointer to an array I, j tail pointer to an array, j odd stop decrementing the pointer encountered, I encountered Even Stop pointer is incremented, and the pointer points to exchange two values, the iteration continues to meet two pointers
class Solution {
public:
void reOrderArray(vector<int> &array) {
int i = 0, j = array.size() - 1;
while (i < j) {
while (i < j && array[j] % 2 == 0) j --;
while (i < j && array[i] % 2 == 1) i ++;
swap(array[i], array[j]);
}
}
};