Move all zeros to start and ones to end in an Array of random integers | Utility function to print the contents of an array ; Function that pushes all the zeros to the start and ones to the end of an array ; To store the count of elements which are not equal to 1 ; Traverse the array and calculate count of elements which are not 1 ; Now all non - ones elements have been shifted to front and ' count1' is set as index of first 1. Make all elements 1 from count to end . ; Initialize lastNonBinary position to zero ; Traverse the array and pull non - zero elements to the required indices ; Ignore the 1 's ; Mark the position Of last NonBinary integer ; Place non - zero element to their required indices ; Put zeros to start of array ; Driver code
function printArr ( arr , n ) { for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } function pushBinaryToBorder ( arr , n ) { var count1 = 0 ; for ( var i = 0 ; i < n ; i ++ ) if ( arr [ i ] != 1 ) arr [ count1 ++ ] = arr [ i ] ; while ( count1 < n ) arr [ count1 ++ ] = 1 ; var lastNonOne = 0 ; for ( var i = n - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] == 1 ) continue ; if ( ! lastNonOne ) { lastNonOne = i ; } if ( arr [ i ] != 0 ) arr [ lastNonOne -- ] = arr [ i ] ; } while ( lastNonOne >= 0 ) arr [ lastNonOne -- ] = 0 ; } var arr = [ 1 , 2 , 0 , 0 , 0 , 3 , 6 ] ; var n = arr . length ; pushBinaryToBorder ( arr , n ) ; printArr ( arr , n ) ;