There are many solutions to this problem. I shall start with very simple one.
Solution1: count the number of ones in array and fill the front elements of array with those many ones and rest of the array with zeroes. Following code does that-
void zero_to_front(char* c, int n)
{
int count = 0;
for(int i=0; i<n; i++)
if(c[i] == 1) count++;
for(int i=0; i<n; i++)
if(i<count) c[i]=1;
else c[i] = 0
}
Time complexity is: O(n)
Solution2: Each time you find 0 in array look for 1 in following positions in array and swap it. Following code does that.
void zero_to_front(int*c, int n){
int one_pos = -1;
for (int i = 0; i < n; i++) {
if (c[i] == 0) {
if(one_pos == -1)
one_pos = i+1;
//Find the position of first one
while (one_pos < n && c[one_pos] != 1 )
one_pos++;
//swap(c[i], c[one_pos]);
int temp = c[i];
c[i] = c[one_pos];
c[one_pos] = temp;
}
}
}
Time complexity is: O(n)
Solution3: Sort the array in reverse order. Time complexity is: O(nlogn)