Examples:
Input:
arr[ ] = {1, 0, 2, 1, 1, 0, 2, 0, 1, 0}
Output:
arr[ ] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2}
#include <bits/stdc++.h>
using namespace std;
// Function to sort 0s,1s,2s
void sort(int array[], int n)
{
int a = 0, a1 = 0, a2 = 0;
// Count the number of 0s, 1s and 2s in the array
for (int i = 0; i < n; i++)
{
switch (array[i])
{
case 0:
a++;
break;
case 1:
a1++;
break;
case 2:
a2++;
break;
}
}
int i = 0;
// update 0s in the array
while (a > 0)
{
array[i++] = 0;
a--;
}
// update 1s in the array
while (a1 > 0)
{
array[i++] = 1;
a1--;
}
// update 2s in the array
while (a2 > 0)
{
array[i++] = 2;
a2--;
}
}
// Function to print the array
void printArray(int array[], int n)
{
for (int i = 0; i < n; i++)
cout << array[i] << " ";
cout << endl;
}
// Main function
int main()
{
int array[100], N;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> array[i];
}
// sorting the array
sort(array, array + N);
cout << "Sorted Array" << endl;
printArray(array, N);
return 0;
}
Output:
Enter Number of elements: 10
1 0 2 0 1 0 2 2 1 0
Sorted Array
0 0 0 0 1 1 1 2 2 2
0 Comments