text: 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 code
code: function segregate0and1 ( arr , size ) { let left = 0 , right = size - 1 ; while ( left < right ) { while ( arr [ left ] == 0 && left < right ) left ++ ; while ( arr [ right ] == 1 && left < right ) right -- ; if ( left < right ) { arr [ left ] = 0 ; arr [ right ] = 1 ; left ++ ; right -- ; } } } let arr = [ 0 , 1 , 0 , 1 , 1 , 1 ] ; let i , arr_size = arr . length ; segregate0and1 ( arr , arr_size ) ; document . write ( " " ) ; for ( i = 0 ; i < 6 ; i ++ ) document . write ( arr [ i ] + " " ) ;