Problem no 4: sort the array of 0's,1's,and 2's.


Sort an array of 0s, 1s and 2s
Easy Accuracy: 51.36% Submissions: 42188 Points: 2

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.


Example 1:

Input: 
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2
Explanation:
0s 1s and 2s are segregated 
into ascending order.
Answer:
without using sorting algorithm.

void sort012(int a[], int n)
{
    
   int countofzero=0;
   int countofone=0;
   int countoftwo=0;
 
   for(int i=0;i<n;i++)
   {
      if(a[i]==0)
       {
          countofzero+=1;
       }
       if(a[i]==1)
       {
           countofone+=1;
       }
       if(a[i]==2)
       {
           countoftwo+=1;
       }
   }
 
     vector<int> vec;
   for(int i=0;i<countofzero;i++)
   {
      vec.push_back(0);
   }
   for(int i=0;i<countofone;i++)
   {
          vec.push_back(1);
  }
  for(int i=0;i<countoftwo;i++)
  {
          vec.push_back(2);
  }
 
  for(int i=0;i<n;i++)
  {
      cout<<vec[i]<<" ";
  }
}





By using sorting algorithm:
   void sort012(int a[], int n)
{
    sort(a,a+n);
  for(int i=0;i<n;i++)
  {
      cout<<a[i]<<" ";
  }
}
 

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.


Example 1:

Input: 
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2Second
Explanation:
0s 1s and 2s are segregated 
into ascending order.

Comments

Popular posts from this blog

Problem no 18(array):count the number of pairs in array whose sum is equal to the given number.

convert the integer number to its binary representation.

Tcs assessment problem: museum problem.