[英]How to implement Stack<E> withing <T extends Comparable<T>>?
The program I am writing is to provide a non-recursive implementation for quick sort inside QuickSort class using a stack implementation. 我正在编写的程序是使用堆栈实现提供一个非递归实现,以便在QuickSort类中快速排序。 I feel that my code is correct within the sort() method.
我觉得我的代码在sort()方法中是正确的。 A problem I am having is with intializing Stack due to implementing the Comparable interface.
我遇到的一个问题是由于实现Comparable接口而初始化Stack。 When my method has an "extends Comparable" What should my Stack be parameterized to since E is the wrong parameter for Stack in this situation.
当我的方法有一个“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>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.