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
#include <iostream> NEW_LINE using namespace std ; void swap ( int & a , int & b ) { int temp = a ; a = b ; b = temp ; } void findPermutation ( int N ) { int arr [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } for ( int i = 1 ; i < N ; i += 2 ) { swap ( arr [ i ] , arr [ i - 1 ] ) ; } if ( N % 2 == 1 && N > 1 ) { swap ( arr [ N - 1 ] , arr [ N - 2 ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } int main ( ) { int N = 7 ; findPermutation ( N ) ; return 0 ; }