Solution Review: Sort Stack
This review will provide a detailed analysis of how to sort the elements of a stack.
First solution: Using the sorted insert function
In this approach, we recursively call the sortStack()
function. Then we call the sortedInsert()
function inside the recursion to sort the stack.
Solution code
Go (1.6.2)
Files
package mainfunc sortedInsert(stk *Stack, element int) {var temp intif (stk.Length() == 0 || element > stk.Top()) {stk.Push(element)} else {temp = stk.Pop()sortedInsert(stk, element)stk.Push(temp)}}func sortStack(stk *Stack) {var temp intif (stk.Length() > 0) {temp = stk.Pop()sortStack(stk)sortedInsert(stk, temp)}}// Testing codefunc main() {stk := new(Stack)stk.Push(1)stk.Push(4)stk.Push(3)stk.Push(2)sortStack(stk)stk.Print()}
Time complexity
The time complexity of this approach is ...