Segregate 0 s and 1 s in an array | Function to put all 0 s on left and all 1 s on right ; Initialize left and right indexes ; Increment left index while we see 0 at left ; Decrement right index while we see 1 at right ; If left is smaller than right then there is a 1 at left and a 0 at right . Exchange arr [ left ] and arr [ right ] ; driver program to test
def segregate0and1 ( arr , size ) : NEW_LINE INDENT left , right = 0 , size - 1 NEW_LINE while left < right : NEW_LINE INDENT while arr [ left ] == 0 and left < right : NEW_LINE INDENT left += 1 NEW_LINE DEDENT while arr [ right ] == 1 and left < right : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT if left < right : NEW_LINE INDENT arr [ left ] = 0 NEW_LINE arr [ right ] = 1 NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 1 , 1 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE print ( " Array ▁ after ▁ segregation " ) NEW_LINE print ( segregate0and1 ( arr , arr_size ) ) NEW_LINE