Binary Array Sorting

PROBLEM :

Given a binary array, sort it in non-decreasing order

Input: First line contains an integer denoting the test cases 'T'.  Every test case contains two lines, first line is size and second line is space separated elements of array

Output:  Space separated elements of sorted arrays.  There should be a new line between output of every test case.


Constraints:
1 <= Size of Array <= 1000
10 <= Number of test cases <= 100

Example:

Input:
2
5
1 0 1 1 0
10
1 0 1 1 1 1 1 0 0 0

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

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : O(n^2)
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int main()
 {
int t,no,a[1000],i,j,temp ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
   cin>>a[i] ;
 
   for(i=0;i<no-1;i++)
   {
       for(j=0;j<no-i-1;j++)
       {
           if(a[j]>a[j+1])
           {
               temp=a[j] ;
               a[j]=a[j+1] ;
               a[j+1]=temp ;
           }
       }
   }
 
   for(i=0;i<no;i++)
   cout<<a[i]<<" " ;
 
   cout<<endl ;
}
return 0;
}

-------------------------------------------------------------------------------
BETTER SOLUTION : O(n)
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int main()
 {
int t,no,a[1000],i,j,zero ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
   cin>>a[i] ;
 
   zero=0 ;
 
   for(i=0;i<no;i++)
   {
       if(a[i]==0)
       zero++ ;
   }
 
   for(i=0;i<zero;i++)
       a[i]=0 ;
   for(i=zero;i<no;i++)
       a[i]=1 ;
     
  for(i=0;i<no;i++)
  cout<<a[i]<<" " ;
 
  cout<<endl ;
}
return 0;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )