Sort an array of 0 s , 1 s , 2 s and 3 s | Function to sort the array having array element only 0 , 1 , 2 , and 3 ; Iterate until mid <= j ; If arr [ mid ] is 0 ; Swap integers at indices i and mid ; Increment i ; Increment mid ; Otherwise if the value of arr [ mid ] is 3 ; Swap arr [ mid ] and arr [ j ] ; Decrement j ; Otherwise if the value of arr [ mid ] is either 1 or 2 ; Increment the value of mid ; Iterate until i <= j ; If arr [ i ] the value of is 2 ; Swap arr [ i ] and arr [ j ] ; Decrement j ; Otherwise , increment i ; Print the sorted array arr [ ] ; Driver Code
def sortArray ( arr , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE mid = 0 NEW_LINE while ( mid <= j ) : NEW_LINE INDENT if ( arr [ mid ] == 0 ) : NEW_LINE INDENT arr [ i ] , arr [ mid ] = arr [ mid ] , arr [ i ] NEW_LINE i += 1 NEW_LINE mid += 1 NEW_LINE DEDENT elif ( arr [ mid ] == 3 ) : NEW_LINE INDENT arr [ mid ] , arr [ j ] = arr [ j ] , arr [ mid ] NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ mid ] == 1 or arr [ mid ] == 2 ) : NEW_LINE INDENT mid += 1 NEW_LINE DEDENT DEDENT while ( i <= j ) : NEW_LINE INDENT if ( arr [ i ] == 2 ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 0 , 2 , 3 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE sortArray ( arr , N ) NEW_LINE DEDENT