Sort the given stack elements based on their modulo with K | Function to sort the stack using another stack based on the values of elements modulo k ; Pop out the first element ; While temporary stack is not empty ; The top of the stack modulo k is greater than ( temp & k ) or if they are equal then compare the values ; Pop from temporary stack and push it to the input stack ; Push temp in temporary of stack ; Push all the elements in the original stack to get the ascending order ; Print the sorted elements ; Driver code
function sortStack ( input , k ) { let tmpStack = [ ] ; while ( input . length != 0 ) { let tmp = input . pop ( ) ; while ( tmpStack . length != 0 ) { let tmpStackMod = tmpStack [ tmpStack . length - 1 ] % k ; let tmpMod = tmp % k ; if ( ( tmpStackMod > tmpMod ) || ( tmpStackMod == tmpMod && tmpStack [ tmpStack . length - 1 ] > tmp ) ) { input . push ( tmpStack [ tmpStack . length - 1 ] ) ; tmpStack . pop ( ) ; } else break ; } tmpStack . push ( tmp ) ; } while ( tmpStack . length != 0 ) { input . push ( tmpStack [ tmpStack . length - 1 ] ) ; tmpStack . pop ( ) ; } while ( input . length != 0 ) { document . write ( input . pop ( ) + " " ) ; } } let input = [ ] ; input . push ( 10 ) ; input . push ( 3 ) ; input . push ( 2 ) ; input . push ( 6 ) ; input . push ( 12 ) ; let k = 4 ; sortStack ( input , k ) ;