Move all zeros to start and ones to end in an Array of random integers | C ++ implementation of the approach ; 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
#include <iostream> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void pushBinaryToBorder ( int arr [ ] , int n ) { int count1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != 1 ) arr [ count1 ++ ] = arr [ i ] ; while ( count1 < n ) arr [ count1 ++ ] = 1 ; int lastNonOne = 0 ; for ( int 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 ; } int main ( ) { int arr [ ] = { 1 , 2 , 0 , 0 , 0 , 3 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pushBinaryToBorder ( arr , n ) ; printArr ( arr , n ) ; return 0 ; }