Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Python C ++ program to sort an array of 0 s 1 s and 2 s . ; Variables to maintain the count of 0 ' s , ▁ ▁ 1' s and 2 's in the array ; Putting the 0 's in the array in starting. ; Putting the 1 ' s ▁ in ▁ the ▁ array ▁ after ▁ the ▁ 0' s . ; Putting the 2 ' s ▁ in ▁ the ▁ array ▁ after ▁ the ▁ 1' s ; Prints the array ; Driver code
import math NEW_LINE def sort012 ( arr , n ) : NEW_LINE INDENT count0 = 0 NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT count0 = count0 + 1 NEW_LINE DEDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT count1 = count1 + 1 NEW_LINE DEDENT if ( arr [ i ] == 2 ) : NEW_LINE INDENT count2 = count2 + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , count0 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT for i in range ( count0 , ( count0 + count1 ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT for i in range ( ( count0 + count1 ) , n ) : NEW_LINE INDENT arr [ i ] = 2 NEW_LINE DEDENT return NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE sort012 ( arr , n ) NEW_LINE printArray ( arr , n ) NEW_LINE