March 22th, 2016.
Move Zeros to the right end but keep the order of non-zero numbers.
#include <stdio.h>
#inlcude <iostream>
#include <vector>
using namespace std;
// move Zeros to the right end of the array.
// classical two pointers problem.
void moveZeroToRight(vector<int>& array) {
if(array.size() <= 1) return; // if the array only has 0-1 values, no need to sort.
int left = 0; // one pointer to remember the left copy.
int i = 0; // one pointer to loop the array.
while(i < array.size()) {
if(array[i] != 0) {
array[left++] = array[i++]; // if it is not zero, copy it to the left end.
} else {
i++; // otherwise, i pointer keeps on moving.
}
}
// copy all non-zeros to the left now. But we need to remember to set the left values to 0.
while(left < array.size()) {
array[left++] = 0;
}
}
// the following is for test purpose.
void printArray(vector<int> array) {
for(int i = 0; i < array.size(); ++i) {
printf("%d\n", array[i]);
}
}
int main(void) {
vector<int> array;
array.push_back(0); array.push_back(1);
moveZeroToRight(array);
printArray(array);
}