Separate 0s and 1s in an array

Question - 
Given an array of 0s and 1s in random order. separate 0s on the left side and 1s on the right side of the array.
Example -
Input : arr[] = {1, 0, 1, 1, 1, 1, 0, 0, 0, 1}
Output : {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}

Approach - 
We count the number of zeros in the array. and then we reinitilize the array with 0s and 1s.

Implementation - 

#include<iostream>
using namespace std;
void separate(int arr[],int n)
{
    int zeros=0;
    for(int i=0;i<n;i++){
        if(arr[i]==0)
            zeros++;
    }
    for(int i=0;i<zeros;i++)
        arr[i]=0;
    for(int i=zeros;i<n;i++)
        arr[i]=1;

}
int main()
{
    int n;
    cout<<"Enter the number of the elements : ";cin>>n;
    int arr[n];
    cout<<"Enter elements : "<<endl;
    for(int i=0;i<n;i++)
        cin>>arr[i];

    separate(arr,n);
    for(int i=0;i<n;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;

}
Time complexity - O(n)

Comments