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
def sortStack ( input1 , k ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while ( len ( input1 ) != 0 ) : NEW_LINE INDENT tmp = input1 [ - 1 ] NEW_LINE input1 . pop ( ) NEW_LINE while ( len ( tmpStack ) != 0 ) : NEW_LINE INDENT tmpStackMod = tmpStack [ - 1 ] % k NEW_LINE tmpMod = tmp % k NEW_LINE if ( ( tmpStackMod > tmpMod ) or ( tmpStackMod == tmpMod and tmpStack [ - 1 ] > tmp ) ) : NEW_LINE INDENT input1 . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT tmpStack . append ( tmp ) NEW_LINE DEDENT while ( len ( tmpStack ) != 0 ) : NEW_LINE INDENT input1 . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT while ( len ( input1 ) != 0 ) : NEW_LINE INDENT print ( input1 [ - 1 ] , end = " ▁ " ) NEW_LINE input1 . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input1 = [ ] NEW_LINE input1 . append ( 10 ) NEW_LINE input1 . append ( 3 ) NEW_LINE input1 . append ( 2 ) NEW_LINE input1 . append ( 6 ) NEW_LINE input1 . append ( 12 ) NEW_LINE k = 4 NEW_LINE sortStack ( input1 , k ) NEW_LINE DEDENT