Sort the given stack elements based on their modulo with K | C # implementation of the above approach ; 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
using System ; using System . Collections ; class GFG { static void sortStack ( Stack input , int k ) { Stack tmpStack = new Stack ( ) ; while ( input . Count != 0 ) { int tmp = ( int ) input . Peek ( ) ; input . Pop ( ) ; while ( tmpStack . Count != 0 ) { int tmpStackMod = ( int ) tmpStack . Peek ( ) % k ; int tmpMod = tmp % k ; if ( ( tmpStackMod > tmpMod ) || ( tmpStackMod == tmpMod && ( int ) tmpStack . Peek ( ) > tmp ) ) { input . Push ( ( int ) tmpStack . Peek ( ) ) ; tmpStack . Pop ( ) ; } else break ; } tmpStack . Push ( tmp ) ; } while ( tmpStack . Count != 0 ) { input . Push ( ( int ) tmpStack . Peek ( ) ) ; tmpStack . Pop ( ) ; } while ( input . Count != 0 ) { Console . Write ( ( int ) input . Peek ( ) + " ▁ " ) ; input . Pop ( ) ; } } public static void Main ( string [ ] args ) { Stack input = new Stack ( ) ; input . Push ( 10 ) ; input . Push ( 3 ) ; input . Push ( 2 ) ; input . Push ( 6 ) ; input . Push ( 12 ) ; int k = 4 ; sortStack ( input , k ) ; } }