Segregate 0’s, 1’s and 2’s in an array

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

Here, in this section we will discuss the C program for segregate in an array :

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

INPUT
0 1 2 0 1 1 1 1 1 0 1 2 1 0 2 2 2 0 1 2 0 1

OUTPUT
0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2

TCS Coding Questions 2022 Day 5 Slot 1

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 3 say count[3] for counting the frequency of 0’s, 1’s ad 2’s respectively.
  • Now, print the elements on the basis of their counts in the count[3].

Code based on above Algorithm

#include <stdio.h>

int main()

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

int count[3]={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 :

1 0 1 2 1 2 0 1 2 0 2 2

0 0 0 1 1 1 1 2 2 2 2 2