Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 10^5
0 <= A[i] <= 2
//Here we have a function
1: void sort012(int a[], int n)
2: {
3: int c0=0,c1=0,c2=0;
4: c0=count(a,a+n,0);
5: c1=count(a,a+n,1);
6: c2=count(a,a+n,2);
7: int k=0;
8: for(int i=0;i<c0;i++)
9: a[k++]=0;
10: for(int i=0;i<c1;i++)
11: a[k++]=1;
12: for(int i=0;i<c2;i++)
13: a[k++]=2;
14: }
//Here we have a full program.
1: #include <bits/stdc++.h>
2: using namespace std;
3: int main()
4: {
5: int arr[5];
6: int n = 5;
7: for(int i = 0 ; i < 5; i++)
8: cin>>arr[i];
9: int c0=0,c1=0,c2=0;
10: count(a,a+n,0);
11: count(a,a+n,1);
12: count(a,a+n,2);
13: int k =0 ;
14: for(int i = 0 ; i < c0 ; i++)arr[k++] = 0;
15: for(int i = 0 ; i < c1 ; i++)arr[k++] = 1;
16: for(int i = 0 ; i < c2 ; i++)arr[k++] = 2;
17: for(int i = 0 ; i < n ; i++)
18: cout<<arr[i]<<endl;
19: return 0;
20: }
0 Comments
If you have any doubt then let me know.