text: Minimum adjacent swaps required to Sort Binary array | C # 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
code: using System ; 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 ( ) { int [ ] ar = { 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 } ; Console . WriteLine ( findMinSwaps ( ar , ar . Length ) ) ; } }