Merging and Sorting Two Unsorted Stacks | This is the temporary stack ; 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
let res = [ ] ; let tmpStack = [ ] ; function sortStack ( input ) { while ( input . length != 0 ) { let tmp = input [ input . length - 1 ] ; input . pop ( ) ; while ( tmpStack . length != 0 && tmpStack [ tmpStack . length - 1 ] > tmp ) { input . push ( tmpStack [ tmpStack . length - 1 ] ) ; tmpStack . pop ( ) ; } tmpStack . push ( tmp ) ; } } function sortedMerge ( s1 , s2 ) { while ( s1 . length != 0 ) { res . push ( s1 [ s1 . length - 1 ] ) ; s1 . pop ( ) ; } while ( s2 . length != 0 ) { res . push ( s2 [ s2 . length - 1 ] ) ; s2 . pop ( ) ; } sortStack ( res ) ; } let s1 = [ ] ; let s2 = [ ] ; s1 . push ( 34 ) ; s1 . push ( 3 ) ; s1 . push ( 31 ) ; s2 . push ( 1 ) ; s2 . push ( 12 ) ; s2 . push ( 23 ) ; sortedMerge ( s1 , s2 ) ; document . write ( " " + " " ) ; while ( tmpStack . length != 0 ) { document . write ( tmpStack [ tmpStack . length - 1 ] + " " ) ; tmpStack . pop ( ) ; }