Sorting array using Stacks | C # program to sort an array using stack ; This function return the sorted stack ; pop out the first element ; while temporary stack is not empty and top of stack is smaller than temp ; pop from temporary stack and push it to the input stack ; push temp in tempory of stack ; Push array elements to stack ; Sort the temporary stack ; Put stack elements in arrp [ ] ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static Stack < int > sortStack ( Stack < int > input ) { Stack < int > tmpStack = new Stack < int > ( ) ; while ( input . Count != 0 ) { int tmp = input . Peek ( ) ; input . Pop ( ) ; while ( tmpStack . Count != 0 && tmpStack . Peek ( ) < tmp ) { input . Push ( tmpStack . Peek ( ) ) ; tmpStack . Pop ( ) ; } tmpStack . Push ( tmp ) ; } return tmpStack ; } static void sortArrayUsingStacks ( int [ ] arr , int n ) { Stack < int > input = new Stack < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) input . Push ( arr [ i ] ) ; Stack < int > tmpStack = sortStack ( input ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = tmpStack . Peek ( ) ; tmpStack . Pop ( ) ; } } static void Main ( ) { int [ ] arr = new int [ ] { 10 , 5 , 15 , 45 } ; int n = arr . Length ; sortArrayUsingStacks ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } }