Next higher number using atmost one swap operation | JAVA implementation to find the next higher number using atmost one swap operation ; function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of rightmost digit which has a digit greater to it on its right side ; required digit found , store its ' index ' and break ; if no such digit is found which has a larger digit on its right side ; to store the index of the smallest digit greater than the digit at ' index ' and right to it ; finding the index of the smallest digit greater than the digit at ' index ' and right to it ; swapping the digits ; required number ; Driver program to test above
class GFG { static String nextHighUsingAtMostOneSwap ( String st ) { char num [ ] = st . toCharArray ( ) ; int l = num . length ; int posRMax = l - 1 ; int index = - 1 ; for ( int i = l - 2 ; i >= 0 ; i -- ) { if ( num [ i ] >= num [ posRMax ] ) posRMax = i ; else { index = i ; break ; } } if ( index == - 1 ) return " Not ▁ Possible " ; int greatSmallDgt = - 1 ; for ( int i = l - 1 ; i > index ; i -- ) { if ( num [ i ] > num [ index ] ) { if ( greatSmallDgt == - 1 ) greatSmallDgt = i ; else if ( num [ i ] <= num [ greatSmallDgt ] ) greatSmallDgt = i ; } } char temp = num [ index ] ; num [ index ] = num [ greatSmallDgt ] ; num [ greatSmallDgt ] = temp ; return ( String . valueOf ( num ) ) ; } public static void main ( String [ ] args ) { String num = "218765" ; System . out . println ( " Original ▁ number : ▁ " + num ) ; System . out . println ( " Next ▁ higher ▁ number : ▁ " + nextHighUsingAtMostOneSwap ( num ) ) ; } }