Merging and Sorting Two Unsorted Stacks | 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
def sortStack ( Input ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while len ( Input ) != 0 : NEW_LINE INDENT tmp = Input [ - 1 ] NEW_LINE Input . pop ( ) NEW_LINE while len ( tmpStack ) != 0 and tmpStack [ - 1 ] > tmp : NEW_LINE INDENT Input . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT tmpStack . append ( tmp ) NEW_LINE DEDENT return tmpStack NEW_LINE DEDENT def sortedMerge ( s1 , s2 ) : NEW_LINE INDENT res = [ ] NEW_LINE while len ( s1 ) != 0 : NEW_LINE INDENT res . append ( s1 [ - 1 ] ) NEW_LINE s1 . pop ( ) NEW_LINE DEDENT while len ( s2 ) != 0 : NEW_LINE INDENT res . append ( s2 [ - 1 ] ) NEW_LINE s2 . pop ( ) NEW_LINE DEDENT return sortStack ( res ) NEW_LINE DEDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE s1 . append ( 34 ) NEW_LINE s1 . append ( 3 ) NEW_LINE s1 . append ( 31 ) NEW_LINE s2 . append ( 1 ) NEW_LINE s2 . append ( 12 ) NEW_LINE s2 . append ( 23 ) NEW_LINE tmpStack = [ ] NEW_LINE tmpStack = sortedMerge ( s1 , s2 ) NEW_LINE print ( " Sorted ▁ and ▁ merged ▁ stack ▁ : " ) NEW_LINE while len ( tmpStack ) != 0 : NEW_LINE INDENT print ( tmpStack [ - 1 ] , end = " ▁ " ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT