Find permutation of [ 1 , N ] such that ( arr [ i ] != i + 1 ) and sum of absolute difference between arr [ i ] and ( i + 1 ) is minimum | Function to generate the permutation of the first N natural numbers having sum of absolute difference between element and indices as minimum ; Initialize array arr [ ] from 1 to N ; Swap alternate positions ; Check N is greater than 1 and N is odd ; Swapping last two positions ; Print the permutation ; Driver code
function findPermutation ( N ) { var i ; var arr = new Array ( N ) ; for ( i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } for ( i = 1 ; i < N ; i += 2 ) { var temp = arr [ i ] ; arr [ i ] = arr [ i - 1 ] ; arr [ i - 1 ] = temp ; } if ( N % 2 == 1 && N > 1 ) { var temp = arr [ N - 1 ] ; arr [ N - 1 ] = arr [ N - 2 ] ; arr [ N - 2 ] = temp ; } for ( i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } var N = 7 ; findPermutation ( N ) ;