Sort an array of 0 s , 1 s and 2 s | Utility function to print 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 ; Prthe sorted array ; Driver code
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT cnt0 = 0 NEW_LINE cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT elif arr [ i ] == 1 : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT elif arr [ i ] == 2 : NEW_LINE INDENT cnt2 += 1 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while ( cnt0 > 0 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE i += 1 NEW_LINE cnt0 -= 1 NEW_LINE DEDENT while ( cnt1 > 0 ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE i += 1 NEW_LINE cnt1 -= 1 NEW_LINE DEDENT while ( cnt2 > 0 ) : NEW_LINE INDENT arr [ i ] = 2 NEW_LINE i += 1 NEW_LINE cnt2 -= 1 NEW_LINE DEDENT printArr ( arr , n ) NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE