![]() |
VOOZH | about |
Given a stack of integers, sort it in ascending order using another temporary stack.
Examples:
Input: [34, 3, 31, 98, 92, 23]
Output: [3, 23, 31, 34, 92, 98]
Explanation: After Sorting the given array it would be look like as [3, 23, 31, 34, 92, 98]
Input: [3, 5, 1, 4, 2, 8]
Output: [1, 2, 3, 4, 5, 8]
To sort a stack of intergers using an extra stack (
tmpStack), first, create an emptytmpStack. Then, while the input stack is not empty, pop the top element (temp). IftmpStackhas smaller elements on top, move them back to the input stack. Finally, pushtempintotmpStack. Repeat this process until all elements are sorted intmpStackin ascending order.
input: [34, 3, 31, 98, 92, 23]
Element taken out: 23
input: [34, 3, 31, 98, 92]
tmpStack: [23]
Element taken out: 92
input: [34, 3, 31, 98]
tmpStack: [23, 92]
Element taken out: 98
input: [34, 3, 31]
tmpStack: [23, 92, 98]
Element taken out: 31
input: [34, 3, 98, 92]
tmpStack: [23, 31]
Element taken out: 92
input: [34, 3, 98]
tmpStack: [23, 31, 92]
Element taken out: 98
input: [34, 3]
tmpStack: [23, 31, 92, 98]
Element taken out: 3
input: [34, 98, 92, 31, 23]
tmpStack: [3]
Element taken out: 23
input: [34, 98, 92, 31]
tmpStack: [3, 23]
Element taken out: 31
input: [34, 98, 92]
tmpStack: [3, 23, 31]
Element taken out: 92
input: [34, 98]
tmpStack: [3, 23, 31, 92]
Element taken out: 98
input: [34]
tmpStack: [3, 23, 31, 92, 98]
Element taken out: 34
input: [98, 92]
tmpStack: [3, 23, 31, 34]
Element taken out: 92
input: [98]
tmpStack: [3, 23, 31, 34, 92]
Element taken out: 98
input: []
tmpStack: [3, 23, 31, 34, 92, 98]
Final sorted stack: [3, 23, 31, 34, 92, 98]
3 23 31 34 92 98
Time Complexity: O(n2), where n is the total number of integers in the given stack.
Auxiliary Space: O(n)