Move all zeros to start and ones to end in an Array of random integers | Utility function to print the contents of an array ; Function that pushes all the zeros to the start and ones to the end of an array ; To store the count of elements which are not equal to 1 ; Traverse the array and calculate count of elements which are not 1 ; Now all non - ones elements have been shifted to front and ' count1' is set as index of first 1. Make all elements 1 from count to end . ; Initialize lastNonBinary position to zero ; Traverse the array and pull non - zero elements to the required indices ; Ignore the 1 's ; Mark the position Of last NonBinary integer ; Place non - zero element to their required indices ; Put zeros to start of 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 pushBinaryToBorder ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != 1 ) : NEW_LINE INDENT arr [ count1 ] = arr [ i ] NEW_LINE count1 += 1 NEW_LINE DEDENT DEDENT while ( count1 < n ) : NEW_LINE INDENT arr [ count1 ] = 1 NEW_LINE count1 += 1 NEW_LINE DEDENT lastNonOne = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not lastNonOne ) : NEW_LINE INDENT lastNonOne = i NEW_LINE DEDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT arr [ lastNonOne ] = arr [ i ] NEW_LINE lastNonOne -= 1 NEW_LINE DEDENT DEDENT while ( lastNonOne >= 0 ) : NEW_LINE INDENT arr [ lastNonOne ] = 0 NEW_LINE lastNonOne -= 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 0 , 0 , 0 , 3 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE pushBinaryToBorder ( arr , n ) NEW_LINE printArr ( arr , n ) NEW_LINE DEDENT