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
import java . util . * ; class GFG { static void findPermutation ( int N ) { int [ ] arr = new int [ N ] ; int temp ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } for ( int i = 1 ; i < N ; i += 2 ) { temp = arr [ i ] ; arr [ i ] = arr [ i - 1 ] ; arr [ i - 1 ] = temp ; } if ( N % 2 == 1 && N > 1 ) { temp = arr [ N - 1 ] ; arr [ N - 1 ] = arr [ N - 2 ] ; arr [ N - 2 ] = temp ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 7 ; findPermutation ( N ) ; } }