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 Code
< ? php function nxtHighUsingAtMostOneSwap ( $ num ) { $ l = strlen ( $ num ) ; $ posRMax = $ l - 1 ; $ index = -1 ; for ( $ i = $ l - 2 ; $ i >= 0 ; $ i -- ) { if ( $ num [ $ i ] >= $ num [ $ posRMax ] ) $ posRMax = $ i ; else { $ index = $ i ; break ; } } if ( $ index == -1 ) return " Not ▁ Possible " ; $ greatSmallDgt = -1 ; for ( $ i = $ l - 1 ; $ i > $ index ; $ i -- ) { if ( $ num [ $ i ] > $ num [ $ index ] ) { if ( $ greatSmallDgt == -1 ) $ greatSmallDgt = $ i ; else if ( $ num [ $ i ] <= $ num [ $ greatSmallDgt ] ) $ greatSmallDgt = $ i ; } } $ temp = $ num [ $ index ] ; $ num [ $ index ] = $ num [ $ greatSmallDgt ] ; $ num [ $ greatSmallDgt ] = $ temp ; return $ num ; } $ num = "218765" ; echo " Original ▁ number : ▁ " . $ num . " STRNEWLINE " ; echo " Next ▁ higher ▁ number : ▁ " . nxtHighUsingAtMostOneSwap ( $ num ) ; ? >