Problem no 4: sort the array of 0's,1's,and 2's.
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.
without using sorting algorithm.
void sort012(int a[], int n)
{
int countofzero=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);
{
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<countoftwo;i++)
{
vec.push_back(2);
}
for(int i=0;i<n;i++)
{
cout<<vec[i]<<" ";
}
}
for(int i=0;i<n;i++)
{
cout<<vec[i]<<" ";
}
}
By using sorting algorithm:
void sort012(int a[], int n)
{
sort(a,a+n);
{
sort(a,a+n);
for(int i=0;i<n;i++)
{
cout<<a[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
Post a Comment