Merging and Sorting Two Unsorted Stacks | C # program to merge to unsorted stacks into a third stack in sorted way . ; Sorts input stack and returns sorted stack . ; pop out the first element ; while temporary stack is not empty and top of stack is greater than temp ; pop from temporary stack and push it to the input stack ; push temp in temporary of stack ; Push contents of both stacks in result ; Sort the result stack . ; main function ; This is the temporary stack
using System ; using System . Collections . Generic ; class GFG { static Stack < int > sortStack ( ref 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 Stack < int > sortedMerge ( ref Stack < int > s1 , ref Stack < int > s2 ) { Stack < int > res = new Stack < int > ( ) ; while ( s1 . Count != 0 ) { res . Push ( s1 . Peek ( ) ) ; s1 . Pop ( ) ; } while ( s2 . Count != 0 ) { res . Push ( s2 . Peek ( ) ) ; s2 . Pop ( ) ; } return sortStack ( ref res ) ; } static void Main ( ) { Stack < int > s1 = new Stack < int > ( ) ; Stack < int > s2 = new Stack < int > ( ) ; s1 . Push ( 34 ) ; s1 . Push ( 3 ) ; s1 . Push ( 31 ) ; s2 . Push ( 1 ) ; s2 . Push ( 12 ) ; s2 . Push ( 23 ) ; Stack < int > tmpStack = new Stack < int > ( ) ; tmpStack = sortedMerge ( ref s1 , ref s2 ) ; Console . Write ( " Sorted ▁ and ▁ merged ▁ stack ▁ : STRNEWLINE " ) ; while ( tmpStack . Count != 0 ) { Console . Write ( tmpStack . Peek ( ) + " ▁ " ) ; tmpStack . Pop ( ) ; } } }