Minimum adjacent swaps required to Sort Binary array | Java code to find minimum number of swaps to sort a 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
class gfg { static int findMinSwaps ( int arr [ ] , int n ) { int noOfZeroes [ ] = new int [ n ] ; int i , 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 ; } public static void main ( String args [ ] ) { int ar [ ] = { 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 } ; System . out . println ( findMinSwaps ( ar , ar . length ) ) ; } }