Minimum adjacent swaps required to Sort Binary array | Function to find minimum swaps to sort an array of 0 s and 1 s . ; Array to store count of zeroes ; Count number of zeroes on right side of every one . ; Count total number of swaps by adding number of zeroes on right side of every one . ; Driver code
< ? php function findMinSwaps ( $ arr , $ n ) { $ noOfZeroes [ $ n ] = array ( ) ; $ noOfZeroes = array_fill ( 0 , $ n , true ) ; $ count = 0 ; $ noOfZeroes [ $ n - 1 ] = 1 - $ arr [ $ n - 1 ] ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { $ noOfZeroes [ $ i ] = $ noOfZeroes [ $ i + 1 ] ; if ( $ arr [ $ i ] == 0 ) $ noOfZeroes [ $ i ] ++ ; } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] == 1 ) $ count += $ noOfZeroes [ $ i ] ; } return $ count ; } $ arr = array ( 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ) ; $ n = sizeof ( $ arr ) ; echo findMinSwaps ( $ arr , $ n ) ; ? >