java - 如何使用 <T extends Comparable<T>> 实现 Stack<E> ?

标签 java stack quicksort comparable non-recursive

我正在编写的程序是使用堆栈实现在 QuickSort 类中提供快速排序的非递归实现。我觉得我的代码在 sort() 方法中是正确的。我遇到的一个问题是由于实现了 Comparable 接口(interface)而初始化堆栈。当我的方法有一个“extends Comparable”时,我的 Stack 应该参数化为什么,因为在这种情况下 E 是 Stack 的错误参数。

   package edu.csus.csc130.spring2017.assignment2;
   import java.util.Stack;
   public class QuickSort{

       // provide non-recursive version of quick sort
       // hint: use stack to stored intermediate results
       // java.util.Stack can be used as stack implementation
       public static <T extends Comparable<T>> void sort(T[] a) {
           Stack<E> stack = new Stack<E>(); //something wrong will <E> i think
           stack.push(0);
           stack.push(a.length);
           while (!stack.isEmpty()) {
               int hi = (int) stack.pop();
               int lo = (int) stack.pop();
               if (lo < hi) {
               // everything seems good up til here
               int p = partition(a, lo, hi);
               stack.push(lo);
               stack.push(p - 1);
               stack.push(p + 1);
               stack.push(hi);

               }
           }        
           throw new UnsupportedOperationException();
       }

       // Partition into a[lo..j-1], a[j], a[j+1..hi]
       private static <T extends Comparable<T>> int partition(T[] a, int lo, int   hi)    { 
           int i = lo, j = hi + 1; // left and right scan indices
           T v = a[lo]; // the pivot

           while (true) { // Scan right, scan left, check for scan complete, and exchange
                while (SortUtils.isLessThan(a[++i], v)) {//++i is evaluated to i+1 
                   if (i == hi) {
                        break;
                   }
               }
               while (SortUtils.isLessThan(v, a[--j])) {//--j is evaluated to j-1
                   if (j == lo) {
                       break;
                   }
               }
               if (i >= j) {
                   break;
               }

               SortUtils.swap(a, i, j);
           }

           SortUtils.swap(a, lo, j); // Put v = a[j] into position
           return j; 
       }

   }

最佳答案

您将压入和弹出与您的 T 无关的整数。类型,所以您可能想使用 Stack<Integer> .

关于java - 如何使用 <T extends Comparable<T>> 实现 Stack<E> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42712748/

相关文章:

haskell - 如何优化并行排序以提高时间性能?

java - Simpledateformat 不解析毫秒

java - 共享首选项和单选按钮我无法正确保存一个单选按钮状态

java - 如何释放JScrollpane使其不总是拖到底部?

c - 将数据从结构体插入 C 中的堆栈

c - 我的解决迷宫的代码进入无限循环

java错误: cannot find symbol stack.大小()

c++ - 霍尔分区无法正常工作(快速排序)

algorithm - 随机快速排序划分概率

java - 试图弄清楚两条线段是否相交