Minimum number of swaps required to make parity of array elements same as their indices | Java program for the above approach ; Function to count the minimum number of swaps required to make the parity of array elements same as their indices ; Stores count of even and odd array elements ; Traverse the array ; Check if indices and array elements are not of the same parity ; If index is even ; Update even ; Update odd ; Condition for not possible ; Otherwise ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void minimumSwaps ( int arr [ ] , int N ) { int even = 0 , odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 != i % 2 ) { if ( i % 2 == 0 ) { even ++ ; } else { odd ++ ; } } } if ( even != odd ) { System . out . println ( - 1 ) ; } else { System . out . println ( even ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 7 , 6 } ; int N = arr . length ; minimumSwaps ( arr , N ) ; } }