Lexicographically smallest permutation of the array possible by at most one swap | C # program for the above approach ; 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 ; Driver Code ; Given array ; Store the size of the array
using System ; class GFG { static void print ( int [ ] arr ) { foreach ( int element in arr ) { Console . Write ( element + " ▁ " ) ; } } static void makeLexicographically ( int [ ] arr , int length ) { int index = 0 ; int temp = 0 ; int check = 0 ; int condition = 0 ; int element = 0 ; for ( int i = 0 ; i < length ; ++ 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 ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int N = arr . Length ; makeLexicographically ( arr , N ) ; } }