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 above functions
class Segregate { void segregate0and1 ( int arr [ ] , int size ) { int 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 -- ; } } } public static void main ( String [ ] args ) { Segregate seg = new Segregate ( ) ; int arr [ ] = new int [ ] { 0 , 1 , 0 , 1 , 1 , 1 } ; int i , arr_size = arr . length ; seg . segregate0and1 ( arr , arr_size ) ; System . out . print ( " Array ▁ after ▁ segregation ▁ is ▁ " ) ; for ( i = 0 ; i < 6 ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }