Lexicographically largest permutation possible by a swap that is smaller than a given array | Function to lexicographic largest permutation possible by a swap that is smaller than given array ; Find the index of first element such that arr [ i ] > arr [ i + 1 ] ; If the array is sorted in increasing order ; Find the index of first element which is smaller than arr [ i ] ; If arr [ j ] = = arr [ j - 1 ] ; Decrement j ; Swap the element ; Print the array arr [ ] ; Driver Code
function findPermutation ( arr ) { let N = arr . length ; let i = N - 2 ; while ( i >= 0 && arr [ i ] <= arr [ i + 1 ] ) i -- ; if ( i == - 1 ) { document . write ( " " ) ; return ; } let j = N - 1 ; while ( j > i && arr [ j ] >= arr [ i ] ) j -- ; while ( j > i && arr [ j ] == arr [ j - 1 ] ) { j -- ; } let temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; for ( let it in arr ) { document . write ( arr [ it ] + " " ) ; } } let arr = [ 1 , 2 , 5 , 3 , 4 , 6 ] ; findPermutation ( arr ) ;