Segregate 0's and 1's in an array

Given an array arr[] containing 0’s and 1’s (only),  segregate the array such that all 0’s are on the left side and all 1’s are on the right side of the array. 

Approach:

For the given array, find the sum of the array which gives the total count of 1’s in the array. Now, subtract that value from the size of the array, which gives a count of 0’s in the array. Print 0’s and 1’s with respect to their count values respectively.

For example,

doc3

Time complexity:  O(n)

Program:

{tab title="C++" class="green"}


/* This code is contributed by Tangudu Sai Kiran. */
//C++ program to sort array containing only 0’ s and 1’s
#include <bits/stdc++.h>
using namespace std;
void sortArray(int n, int arr[])
{
    int no_of_ones = 0;
    
    //counting total number of 1’s
    for(int i = 0; i < n; i++)
    no_of_ones = no_of_ones + arr[i];
    
    //finding total count of 0’s
    int no_of_zeros = n - no_of_ones;
	 
    //displaying the output array
    for(int i = 0; i < no_of_zeros; i++)
        cout<<"0 ";
        
    for(int i = 0; i < no_of_ones; i++)
        cout<<"1 ";
}
int main()
{
    int arr[]={0, 1, 0, 1 ,0 ,1 ,0};
    int n = sizeof(arr)/sizeof(arr[0]);
    //function call
    sortArray(n, arr);                                   
    return 0;
}

{tab title="Java" class="orange"}


/* This code is contributed by Tammisetti Naveen */
//JAVA program to sort array containing only 0’s and 1’s
public class Main {
    public static void SegregateOperation(int n,int arr[])
	{
		int total_sum=0, no_of_zeroes=0;
		
		//computing sum of the array
		for(int i = 0; i < n; i++)
			total_sum += arr[i];
		no_of_zeroes = n - total_sum;
		
		System.out.print("Array after Segregation of 0's and 1's: " );
		for(int i = 0; i < no_of_zeroes; i++)
			System.out.print("0 ");
		for(int i = no_of_zeroes; i < n; i++)
			System.out.print("1 ");
	}
	
	public static void main(String[] args) {
		int arr[]= {0,1,0,0,1,0,1};
		int n=arr.length;
		SegregateOperation(n,arr);
	}

}

{tab title="python" class="blue"}

# Code written by arun reddy

def segregateOperation(array):
    total_sum,no_of_zeroes=0,0
    n=len(array)
    for i in array:
        total_sum+=i
    print("Array after Segregation of 0's and 1's: ",end=" ")
    no_of_zeroes=n-total_sum
    for i in range(no_of_zeroes):
        print(0,end=" ")
    for i in range(no_of_zeroes,n):
        print(1,end=" ")
if __name__=='__main__':
    array=[0,1,1,0,1,0,1]
    segregateOperation(array)

{/tabs}

Output:

Array after segregation is : 0 0 0 0 1 1 1

Contributors for this Article: Tangudu Sai Kiran, Tammisetti Naveen, Arun Reddy