简体   繁体   English

按升序排序堆栈?

[英]Sorting a Stack in Ascending Order?

What is the best method for sorting a stack in ascending order? 按升序排序堆栈的最佳方法是什么 I came across this interview question, and I was running into some problems for the best and most efficient solution. 遇到了这个面试问题,我遇到了一些问题,以获得最佳和最有效的解决方案。

There are two methods that I can think of. 我能想到两种方法。

  1. To pop all the contents of the stack and store them in an array, and then sort the array in 弹出堆栈的所有内容并将它们存储在一个数组中,然后对该数组进行排序
    O(nLog n) and then push the contents back the stack. O(nLog n)然后将内容推回堆栈。 Not the best way.... 不是最好的方式....

  2. Do the recursive implementation of the stack for sorting it 执行堆栈的递归实现以对其进行排序

void sort(stack)
{
    type x;

    if (!isEmpty(stack)) {
        x = pop(stack);
        sort(stack);
        insert(x, stack);
    }           
}

void insert(x, stack)
{
    type y;

    if (!isEmpty(stack) && top(stack) < x) {
        y = pop(stack);
        insert(x, stack);
        push(y, stack);
    } 
    else {
        push(x, stack);
    }
} 

But the 2nd method seems to be making too many recursive calls and the overhead will be a problem if the stack happens to be really big. 但是第二种方法似乎是进行了太多的递归调用,如果堆栈真的很大,那么开销将是一个问题。

Is it possible to solve this problem in a much better way for the best space and time complexity? 是否有可能以更好的方式解决这个问题,以获得最佳的空间和时间复杂度?

There are so many recursive calls, (overlapping subproblems), is this a contender for dynamic programming type of problems? 有很多递归调用(重叠的子问题),这是dynamic programming类型问题的竞争者吗?

What would be the best way to solve this? 解决这个问题的最佳方法是什么? ?

It's a stack. 这是一个堆栈。 You can't see anything but the top value. 你看不到除了最高价值之外的任何东西。 You'll have to pop everything at least once, and push everything at least once. 你必须至少弹出一次,然后至少推送一次。 The first method is fine. 第一种方法很好。

If the stack operations are expensive but you have a time deadline, use insertion sort as you're popping and you can push as soon as your last pop is done. 如果堆栈操作很昂贵,但你有一个时间截止日期,请在弹出时使用插入排序,并且可以在完成最后一次弹出后立即按下。 But you're saying this is in C++ so I doubt we are considering such a scenario. 但是你说这是用C ++编写的,所以我怀疑我们是在考虑这种情况。

You can solve by eliminating the recursion. 您可以通过消除递归来解决。 For this you just use a loop iterating under a stack until it is empty. 为此,您只需在堆栈下使用循环迭代,直到它为空。

For example, pseudo code: 例如,伪代码:

Linekd Stack stack = new List ();

while stack is not empty then

     element <- stack removes peek

     / / Recursiong
     push new elements on stack

end

This problem cant have complexity less than O(n^2). 这个问题的复杂性不能小于O(n ^ 2)。 For further reference refer here 有关详细参考,请参阅此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM