problem no 45:(sorting problem):binary array sorting .

 QUESTIONS:

Given a binary array A[] of size N. The task is to arrange the array in increasing order.
Note: The binary array contains only 0  and 1.
 

Example 1:

Input: 
5
1 0 1 1 0

Output: 
0 0 1 1 1

Explanation: 
After arranging the elements in 
increasing order, elements will be as 0 0 1 1 1.

Example 2:

Input:
10
1 0 1 1 1 1 1 0 0 0

Output: 
0 0 0 0 1 1 1 1 1 1

Explanation: 
After arranging the elements in 
increasing ordeR, elements will be 
0 0 0 0 1 1 1 1 1 1.
 
 

 ANSWER:

 void binSort(int a[], int n)

{
  int countofzero=0;int countofone=0;
 

 for(int i=0;i<n;i++)
  {
      if(a[i]==0)
      {
          countofzero=countofzero+1;
      }
      else
      {
          countofone=countofone+1;
      }
  }
  for(int i=0;i<countofzero;i++)
  {
      a[i]=0;
  }
 
  for(int i=countofzero;i<n;i++)
  {
      a[i]=1;
  }
 
 
 
}

 

 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.