Lexicographically smallest permutation of the array possible by at most one swap | C ++ implementation of 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
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void print ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void makeLexicographically ( int arr [ ] , int N ) { int index = 0 ; int temp = 0 ; int check = 0 ; int condition = 0 ; int element = 0 ; for ( int 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 ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeLexicographically ( arr , N ) ; return 0 ; }