One stack implements another stack sort

One stack implements another stack sort

topic

The elements in a stack are shaped, and now I want to sort this stack from the top to the bottom of the stack, and it is allowed to apply for a stack. There are no other data structures. It is allowed to apply for new variables, how to complete the sorting?

Realization ideas

1. Set the stack to be sorted to stack, the auxiliary stack is help, and the current value popped from the stack is curt
2. Pop the stack in turn, and determine the relationship between the popped value curt and the top element of the help stack. If curt is small, Just pop the top element of the help stack and push it into the stack. On the contrary, push curt into the help and continue to loop until the length of the stack is 0, and the curt is also successfully pushed into the help, and finally returns the help as the result.

Code

//需要排序的栈 stack
//辅助排序的栈 help
//一个人变量存储当前的值 curt
function anthorStackSort(stack){
    
    
let help = [];
let curt = stack.pop()
while(stack.length>0||curt){
    
    
   if(help.length == 0||curt>=help[help.length-1]){
    
    
       help.push(curt)
       curt= stack.pop();
   }else{
    
    
       stack.push(help.pop())
   }
}
return help
}

Simple test

function arraySort(stack){
    
    
    stack.sort(function (x,y) {
    
    
        return x-y;
    });
    return stack
}
var {
    
    Logarithm} = require('./Logarithm')
Logarithm(5,arraySort,anthorStackSort,false)

Code download address

thank

If you feel helpful to your study work, please share it with those who need it, or like and encourage it, thank you for
your support. You can add a favorite, and I will continue to update it. . .

Guess you like

Origin blog.csdn.net/XINpxXIN/article/details/104487999