text: Segregate 0 s and 1 s in an array | C # program to sort a binary array in one pass ; 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
code: using System ; 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 ( ) { 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 ) ; Console . WriteLine ( " Array ▁ after ▁ segregation ▁ is ▁ " ) ; for ( i = 0 ; i < 6 ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } }