【问题标题】:Write a program to sort a stack in ascending order编写程序以升序对堆栈进行排序
【发布时间】:2014-09-06 05:27:44
【问题描述】:

有人可以帮忙看看我的代码吗?非常感谢你的帮助。 输入堆栈是 [5, 2, 1, 9, 0, 10],我的代码给出了输出堆栈 [0, 9, 1, 2, 5, 10],9 不在正确的位置。

import java.util.*;

public class CC3_6 {
public static void main(String[] args) {
    int[] data = {5, 2, 1, 9, 0, 10};
    Stack<Integer> myStack = new Stack<Integer>();
    for (int i = 0; i < data.length; i++){
        myStack.push(data[i]);
    }
    System.out.println(sortStack(myStack));
}

public static Stack<Integer> sortStack(Stack<Integer> origin) {
    if (origin == null)
        return null;
    if (origin.size() < 2)
        return origin;

    Stack<Integer> result =  new Stack<Integer>();
    while (!origin.isEmpty()) {
        int smallest = origin.pop();
        int remainder = origin.size();
        for (int i = 0; i < remainder; i++) {
            int element = origin.pop();
            if (element < smallest) {
                origin.push(smallest);
                smallest = element;                    
            } else {
                origin.push(element);
            }
        }
        result.push(smallest);
    }
    return result;

}

}

【问题讨论】:

  • 这看起来根本不像一个排序算法。在sortStack 内的for 循环中,您将相同的元素推回origin 堆栈,并且从不查看堆栈的其余元素。

标签: java sorting stack


【解决方案1】:
public class ReverseStack {

    public static void main(String[] args) {
        Stack<Integer> stack =new Stack<Integer>();
        stack.add(3);stack.add(0);stack.add(2);stack.add(1);
        sortStack(stack);
        System.out.println(stack.toString());
    }

    public static void sortStack(Stack<Integer> stack){

         int tempElement=stack.pop();
         if(!stack.isEmpty()){
             sortStack(stack);
         }
         insertStack(stack,tempElement);
    }

    private static void insertStack(Stack<Integer> stack, int element) {
        if(stack.isEmpty()){
            stack.push(element);
            return;
        }
        int temp=stack.pop();

        //********* For sorting in ascending order********
        if(element<temp){
            insertStack(stack,element);
            stack.push(temp);
        }else{
            stack.push(temp);
            stack.push(element);
        }
        return;
    }

}

【讨论】:

    【解决方案2】:

    这是我的代码版本,非常容易理解。

    import java.util.Stack;
    
    public class StackSorting {
    
        public static void main(String[] args) {
            Stack<Integer> stack = new Stack<Integer>();
    
            stack.push(12);
            stack.push(100);
            stack.push(13);
            stack.push(50);
            stack.push(4);
    
            System.out.println("Elements on stack before sorting: "+ stack.toString());
    
            stack = sort(stack);
    
            System.out.println("Elements on stack after sorting: "+ stack.toString());
    
        }
    
        private static Stack<Integer> sort(Stack<Integer> stack) {
    
            if (stack.isEmpty()) {
                return null;
            }
    
            Stack<Integer> sortedStack = new Stack<Integer>();
    
            int element = 0;
            while(!stack.isEmpty()) {
                if (stack.peek() <= (element = stack.pop())) {
                    if (sortedStack.isEmpty()) {
                        sortedStack.push(element);
                    } else {
                        while((!sortedStack.isEmpty()) && sortedStack.peek() > element) {
                            stack.push(sortedStack.pop());
                        }
                        sortedStack.push(element);
                    }
                }
            }
    
            return sortedStack;
        }
    }
    

    【讨论】:

      【解决方案3】:
      /** the basic idea is we go on popping one one element from the original
       * stack (s) and we compare it with the new stack (temp) if the popped
       * element from original stack is < the peek element from new stack temp
       * than we push the new stack element to original stack and recursively keep
       * calling till temp is not empty and than push the element at the right
       * place. else we push the element to the new stack temp if original element
       * popped is > than new temp stack. Entire logic is recursive.
       */
      public void sortstk( Stack s )
      {
          Stack<Integer> temp = new Stack<Integer>();
      
          while( !s.isEmpty() )
          {
      
              int s1 = (int) s.pop();
      
              while( !temp.isEmpty() && (temp.peek() > s1) )
              {
                  s.push( temp.pop() );
              }
              temp.push( s1 );
      
          }
      
          // Print the entire sorted stack from temp stack
          for( int i = 0; i < temp.size(); i++ )
          {
              System.out.println( temp.elementAt( i ) );
          }
      
      }
      

      【讨论】:

      • 这个算法效率极低。仅对只有 10000 个项目的 Stack 进行排序就需要 6 多秒。尝试使用此处找到的其他解决方案进行排序 blog.pengyifan.com/sort-a-stack-in-ascending-order-in-on-log-n 和 10000 个项目在大约 100 毫秒内排序。仅供参考,低效排序算法的第一个迹象是嵌套循环,例如您在此处使用的 while/while 循环,即 O(n^2)。您可以有多个不嵌套的顺序 while 循环,并且仍然保持至少 O(n) 解决方案
      【解决方案4】:
      package TwoStackSort;
      import java.util.Random;
      import java.util.Stack;
      
      public class TwoStackSort {
          /**
           *
           * @param stack1 The stack in which the maximum number is to be found.
           * @param stack2 An auxiliary stack to help.
           * @return The maximum integer in that stack.
           */
          private static Integer MaxInStack(Stack<Integer> stack1, Stack<Integer> stack2){
              if(!stack1.empty()) {
                  int n = stack1.size();
                  int a = stack1.pop();
                  for (int i = 0; i < n-1; i++) {
                      if(a <= stack1.peek()){
                          stack2.push(a);
                          a = stack1.pop();
                      }
                      else {
                          stack2.push(stack1.pop());
                      }
                  }
                  return a;
              }
              return -1;
          }
      
          /**
           *
           * @param stack1 The original stack.
           * @param stack2 The auxiliary stack.
           * @param n An auxiliary parameter to keep a record of the levels of recursion.
           */
          private static void StackSort(Stack<Integer> stack1, Stack<Integer> stack2, int n){
              if(n==0){
                  return;
              }
              else{
                  int maxinS1 = MaxInStack(stack1, stack2);
                  StackSort(stack2, stack1, n-1);
                  if(n%2==0){
                      stack2.push(maxinS1);
                  }
                  else{stack1.push(maxinS1);}
              }
          }
          /**
           *
            * @param stack1 The original stack that needs to be sorted.
           * @param stack2 The auxiliary stack.
           * @return The descendingly sorted stack.
           */
          public static Stack<Integer> TwoStackSorter(Stack<Integer> stack1, Stack<Integer> stack2){
              StackSort(stack1, stack2, stack1.size()+stack2.size());
              return (stack1.empty())? stack2:stack1;
          }
      
          public static void main(String[] args) {
              Stack<Integer> stack = new Stack<>();
              Random random = new Random();
              for (int i = 0; i < 50; i++) {
                  stack.push(random.nextInt(51));
              }
              System.out.println("The original stack is: ");
              System.out.print(stack);
              System.out.println("\n" + "\n");
              Stack<Integer> emptyStack = new Stack<>();
              Stack<Integer> res =  TwoStackSorter(stack, emptyStack);
              System.out.println("The sorted stack is: ");
              System.out.print(res);
          }
      }
      

      这是我昨天晚上经过一个小时的头脑风暴后想出的代码。当我解决这个问题的一个版本时,我有一个限制,最多只能使用一个额外的堆栈。这是这个问题的一个强烈的递归解决方案。我使用了 2 种私有方法从堆栈中获取我需要的东西。我真的很喜欢递归在这里的工作方式。基本上,我正在解决的版本需要通过最多使用一个额外的堆栈以升序/降序对堆栈进行排序。请注意,不应使用其他数据结构。

      【讨论】:

        【解决方案5】:

        如果可能的话可以使用堆

        public static void sortStack(Stack<Integer> stack) 
        {
           Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
            while(!stack.isEmpty())
                maxHeap.add(stack.pop());       
            int size = maxHeap.size();
            for(int i=0; i<size; i++)
                stack.push(maxHeap.remove());      
        }
        

        【讨论】:

          猜你喜欢
          • 2011-12-08
          • 2021-11-02
          • 2023-04-11
          • 1970-01-01
          • 2015-01-14
          • 2021-09-03
          • 1970-01-01
          • 2022-10-13
          • 2019-05-05
          相关资源
          最近更新 更多