Sort an array of 0 s , 1 s and 2 s | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to sort the array of 0 s , 1 s and 2 s ; Count the number of 0 s , 1 s and 2 s in the array ; Update the array ; Store all the 0 s in the beginning ; Then all the 1 s ; Finally all the 2 s ; Print the sorted array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void sortArr ( int arr [ ] , int n ) { int i , cnt0 = 0 , cnt1 = 0 , cnt2 = 0 ; for ( i = 0 ; i < n ; i ++ ) { switch ( arr [ i ] ) { case 0 : cnt0 ++ ; break ; case 1 : cnt1 ++ ; break ; case 2 : cnt2 ++ ; break ; } } i = 0 ; while ( cnt0 > 0 ) { arr [ i ++ ] = 0 ; cnt0 -- ; } while ( cnt1 > 0 ) { arr [ i ++ ] = 1 ; cnt1 -- ; } while ( cnt2 > 0 ) { arr [ i ++ ] = 2 ; cnt2 -- ; } printArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; sortArr ( arr , n ) ; return 0 ; }