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
def nextHighUsingAtMostOneSwap ( st ) : NEW_LINE INDENT num = list ( st ) NEW_LINE l = len ( num ) NEW_LINE posRMax = l - 1 NEW_LINE index = - 1 NEW_LINE i = l - 2 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( num [ i ] >= num [ posRMax ] ) : NEW_LINE INDENT posRMax = i NEW_LINE DEDENT else : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT i = i - 1 NEW_LINE DEDENT if ( index == - 1 ) : NEW_LINE INDENT return " Not ▁ Possible " NEW_LINE DEDENT greatSmallDgt = - 1 NEW_LINE i = l - 1 NEW_LINE while i > index : NEW_LINE INDENT if ( num [ i ] > num [ index ] ) : NEW_LINE INDENT if ( greatSmallDgt == - 1 ) : NEW_LINE INDENT greatSmallDgt = i NEW_LINE DEDENT elif ( num [ i ] <= num [ greatSmallDgt ] ) : NEW_LINE INDENT greatSmallDgt = i NEW_LINE DEDENT DEDENT i = i - 1 NEW_LINE DEDENT temp = num [ index ] NEW_LINE num [ index ] = num [ greatSmallDgt ] ; NEW_LINE num [ greatSmallDgt ] = temp ; NEW_LINE return ' ' . join ( num ) NEW_LINE DEDENT num = "218765" NEW_LINE print " Original ▁ number : ▁ " , num NEW_LINE print " Next ▁ higher ▁ number : ▁ " , nextHighUsingAtMostOneSwap ( num ) NEW_LINE