Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition | 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 ; Prlet the minimum swaps ; Given Number N ; Given Permutation of N numbers ; Function Call
function solve ( P , n ) { let arr = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; arr [ 0 ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) arr [ i + 1 ] = P [ i ] ; let cnt = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == i ) { let t = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ i ] ; arr [ i ] = t ; cnt ++ ; } } if ( arr [ n ] == n ) { let t = arr [ n - 1 ] ; arr [ n - 1 ] = arr [ n ] ; arr [ n ] = t ; cnt ++ ; } document . write ( cnt ) ; } let N = 9 ; let P = [ 1 , 2 , 4 , 9 , 5 , 8 , 7 , 3 , 6 ] ; solve ( P , N ) ;