Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition | Java program for the above approach ; Function to find the minimum number of swaps ; New array to convert to 1 - based indexing ; Keeps count of swaps ; Check if it is an ' X ' position ; Corner Case ; Swap ; Print the minimum swaps ; Driver code ; Given Number N ; Given Permutation of N numbers ; Function Call
import java . io . * ; class GFG { static void solve ( int P [ ] , int n ) { int arr [ ] = new int [ n + 1 ] ; arr [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) arr [ i + 1 ] = P [ i ] ; int cnt = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == i ) { int t = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ i ] ; arr [ i ] = t ; cnt ++ ; } } if ( arr [ n ] == n ) { int t = arr [ n - 1 ] ; arr [ n - 1 ] = arr [ n ] ; arr [ n ] = t ; cnt ++ ; } System . out . println ( cnt ) ; } public static void main ( String [ ] args ) { int N = 9 ; int P [ ] = new int [ ] { 1 , 2 , 4 , 9 , 5 , 8 , 7 , 3 , 6 } ; solve ( P , N ) ; } }