Segregate 0’s and 1’s in an array

Segregate 0’s and 1’s in an array in C

Here, in this section we will discuss the C program for segregate 0’s and 1’s in an array :

Given an array with 0’s and 1’s, we are segregating the 0’s and 1’s.

INPUT
0 1 0 1 1 1 1 1 0 1 1 0 0 1 0 1

OUTPUT
0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 

segregate 0's and 1's

Algorithm :

 

  • Take the size of an array from the user and store it in variable N.
  • Declare an array of N size and take the N elements of the array from the user.
  • Declare one array of size 2 say count[2] for counting the frequency of 0’s and 1’s respectively.
  • Now, print the elements on the basis of their counts in the count[2] array.

Code based on above algorithm

#include <stdio.h>

int main()

{
int N;
scanf("%d", &N);

int count[2]={0}, arr[N];

for(int i=0; i<N; i++){

scanf("%d", &arr[i]);
count[arr[i]]++;
}

int i=0;

for(int j=0;j<count[i];j++)
printf("%d ", i);

return 0;
}
Input :

0 1 0 0 1 1 1 0 1 1

Output :

0 0 0 0 1 1 1 1 1 1