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
def findPermutation ( N ) : NEW_LINE INDENT arr = [ i + 1 for i in range ( N ) ] NEW_LINE for i in range ( 1 , N , 2 ) : NEW_LINE INDENT arr [ i ] , arr [ i - 1 ] = arr [ i - 1 ] , arr [ i ] NEW_LINE DEDENT if N % 2 and N > 1 : NEW_LINE INDENT arr [ - 1 ] , arr [ - 2 ] = arr [ - 2 ] , arr [ - 1 ] NEW_LINE DEDENT for i in arr : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE findPermutation ( N ) NEW_LINE DEDENT