Here is my code:
function sort(stack){
if(stack.length > 0){
var x = stack.pop();
sort(stack);
insert(x,stack);
}
}
function insert(x,stack){
if(stack.length>0){
var tops = topr(stack);
if(tops>x){
stack.pop();
insert(x,stack);
stack.push(tops);
}else{
stack.push(x);
}
}
}
function topr(stack){
var t = stack.pop();
stack.push(t);
return t;
}
var stack = [1,3,2];
sort(stack);
console.log(stack);
I had to build this without using an array (recursion).
But it returns void/aka nothing in the console.
Edit:
Full working solution:
function sort(stack) {
if(stack.length > 0) {
var x = stack.pop();
sort(stack);
insert(x,stack);
}
return stack;
}
function insert(x,stack){
if(stack.length>0){
var tops = topr(stack);
if(tops>x){
stack.pop();
insert(x,stack);
stack.push(tops);
}else{
stack.push(x);
}
}else{
stack.push(x);
}
}
function topr(stack){
var t = stack.pop();
stack.push(t);
return t;
}
var stack = [1,3,2];
stack = sort(stack);
console.log(stack);
Because it doesn’t havereturn stackin its end, perhaps? Without explicitreturnstatement function will return undefined when it completes.No, it was only the icing on the cake. In fact, there are several logical errors in this code:
insert()function doesn’t insert a value (x) to an empty stacktopr()function is confusing. For a non-empty stack, it returns its last element (which can be done more efficiently with justreturn stack[stack.length - 1], I guess. But if stack is empty, it pushesundefinedto it (as it’s a result ofpopempty array).