Question:
Sort the given array consisting of binary digits in ascending order(descending order) without storing the values itself in the array and in linear time.
Input:
5
1 1 0 1 0
Output:
0 0 1 1 1
Explanation:
While scanning each element ,check whether it is one or zero and increase its frequency counter by 1 for each occurrence.
At the end of input print the zeroes and ones each one the respective frequency counter times.
In the above example:
1 zeroes=0 ones=1 1 zeroes=0 ones=2 0 zeroes=1 ones=2 1 zeroes=1 ones=3 0 zeroes=2 ones=3
Code:
#include<stdio.h>
int main()
{
int n;// no of elements in the array
scanf("%d",&n);
int ones=0,zeroes=0,a,i,j;
//count for no of zeroes and no of ones
for(i=0;i<n;i++)
{
scanf("%d",&a);
if(a==0)
{
zeroes++;
}
else
{
ones++;
}
}
// zeroes followed by ones
for(i=0;i<zeroes;i++)
{
printf("%d ",0);
}
for(j=0;j<ones;j++)
{
printf("%d ",1);
}
/*
//ones follwed by zeroes
for(j=0;j<ones;j++)
{
printf("%d ",1);
}
for(i=0;i<zeroes;i++)
{
printf("%d ",0);
}
*/
return 0;
}

No comments:
Post a Comment