Minimize Steps required to obtain Sorted Order of an Array | Function to find GCD of two numbers ; Function to calculate the LCM of array elements ; Initialize result ; Function to find minimum steps required to obtain sorted sequence ; Inititalize dat [ ] array for Direct Address Table . ; Calculating steps required for each element to reach its sorted position ; Calculate LCM of the array ; Driver Code
function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function findlcm ( arr , n ) { let ans = 1 ; for ( let i = 1 ; i <= n ; i ++ ) ans = ( ( ( arr [ i ] * ans ) ) / ( gcd ( arr [ i ] , ans ) ) ) ; return ans ; } function minimumSteps ( arr , n ) { let i ; let dat = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; for ( i = 1 ; i <= n ; i ++ ) dat [ arr [ i - 1 ] ] = i ; let b = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; let j = 0 , c ; for ( i = 1 ; i <= n ; i ++ ) { c = 1 ; j = dat [ i ] ; while ( j != i ) { c ++ ; j = dat [ j ] ; } b [ i ] = c ; } document . write ( findlcm ( b , n ) ) ; } let arr = [ 5 , 1 , 4 , 3 , 2 , 7 , 6 ] ; let N = arr . length ; minimumSteps ( arr , N ) ;