I m trying to understand sorting a stack elements using recursion given in http://www.geeksforgeeks.org/sort-a-stack-using-recursion/ Use of any loop constructs like while, for..etc is not allowed. We can only use the following ADT functions on Stack S:
is_empty(S) : Tests whether stack is empty or not.
push(S) : Adds new element to the stack.
pop(S) : Removes top element from the stack.
top(S) : Returns value of the top element. Note that this function does not remove element from the stack. I tried below but getting error
var stack = [-3, 14, 18, -5, 30];
function sortStack() {
if (stack.length > 0) {
temp = stack.pop();
sortStack();
sortedInsert(temp, stack);
}
}
function sortedInsert(element, stack) {
if (stack.length > 0 || element > stack[stack.length - 1]) {
stack.push(element);
} else {
temp = stack.pop();
sortedInsert(element, stack);
stack.push(temp);
}
}
sortStack();
console.log(stack);
RangeError: Maximum call stack size exceeded
at sortedInsert:12:22
at sortedInsert:21:5
at sortedInsert:21:5
at sortedInsert:21:5
at sortedInsert:21:5
at sortedInsert:21:5
With javascript, local (scoped) variables need to be declared as var, otherwise they are static. Without the var before t in sortStack(), t would be a static and just get overwritten with each pop, leaving t == -3 on all the returns from sortStack(). The same issue occurs with x in sortedInsert().
If you just want to sort the array, you can use
sort()
method. Check example below:If you want to understand how to sort array manually, have a look at this ans (Note: below code is copied from same ans):