Lexicographically smallest permutation of the array possible by at most one swap | Function to print the elements of the array arr [ ] ; Traverse the array arr [ ] ; Function to convert given array to lexicographically smallest permutation possible by swapping at most one pair ; Stores the index of the first element which is not at its correct position ; Checks if any such array element exists or not ; Traverse the given array ; If element is found at i ; If the first array is not in correct position ; Store the index of the first elements ; Store the index of the first element ; Swap the pairs ; Print the array ; Given array ; Store the size of the array
function print ( arr , N ) { for ( i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } function makeLexicographically ( arr , N ) { var index = 0 ; var temp = 0 ; var check = 0 ; var condition = 0 ; var element = 0 ; for ( i = 0 ; i < N ; ++ i ) { if ( element == arr [ i ] ) { check = i ; break ; } else if ( arr [ i ] != i + 1 && check == 0 ) { index = i ; check = 1 ; condition = - 1 ; element = i + 1 ; } } if ( condition == - 1 ) { temp = arr [ index ] ; arr [ index ] = arr [ check ] ; arr [ check ] = temp ; } print ( arr , N ) ; } var arr = [ 1 , 2 , 3 , 4 ] var N = arr . length ; makeLexicographically ( arr , N ) ;