Sort an array containing two types of elements | JavaScript program to sort an array with two types of values in one traversal . ; Method for segregation 0 and 1 given input array ; Driver Code
function segregate0and1 ( arr , n ) { let type0 = 0 ; let type1 = n - 1 ; while ( type0 < type1 ) { if ( arr [ type0 ] == 1 ) { arr [ type0 ] = arr [ type0 ] + arr [ type1 ] ; arr [ type1 ] = arr [ type0 ] - arr [ type1 ] ; arr [ type0 ] = arr [ type0 ] - arr [ type1 ] ; type1 -- ; } else { type0 ++ ; } } } let arr = [ 1 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 ] ; segregate0and1 ( arr , arr . length ) ; for ( let i = 0 ; i < arr . length ; i ++ ) document . write ( arr [ i ] + " " ) ;