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
< ? php function segregate0and1 ( & $ arr , $ size ) { $ 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 -- ; } } } $ arr = array ( 0 , 1 , 0 , 1 , 1 , 1 ) ; $ arr_size = sizeof ( $ arr ) ; segregate0and1 ( $ arr , $ arr_size ) ; printf ( " Array ▁ after ▁ segregation ▁ is ▁ " ) ; for ( $ i = 0 ; $ i < 6 ; $ i ++ ) echo ( $ arr [ $ i ] . " ▁ " ) ; ? >