【发布时间】:2017-03-12 22:34:22
【问题描述】:
我正在尝试实现一个迭代运行的快速排序方法。我使用堆栈来保存信息。它还将使用分区来实现这一点。我知道底部的分区代码部分很好,它只是它的第一个有问题的块。不过,出于某种原因,我的代码并没有按照它的设想做。对java不太有经验,所以如果有人看到任何会抛出标志的错误,将不胜感激!
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<Integer> stack = new Stack<Integer>();
stack.push(0);
stack.push(a.length);
while (!stack.isEmpty())
{
int i = 0;
int hi = a[i]
hi = stack.pop();
int lo = stack.pop();
if (hi - lo < 2) {
continue;
}
int j = partition(a, lo, hi);
j = hi + ((lo - hi) / 2);
stack.push(j - 1);
stack.push(hi);
stack.push(lo);
stack.push(j);
}
// return;
}
//THIS SECTION OF CODE BELOW SHOULD BE FINE
// 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;
}
}
测试代码
package edu.csus.csc130.spring2017.assignment2;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
public class
QuickSortTest {
@Test
public void testSort1() {
Integer[] a = {17};
Integer[] expected = {17};
QuickSort.sort(a);
System.out.println(Arrays.toString(a));
Assert.assertArrayEquals(expected, a);
}
@Test
public void testSort2() {
Integer[] a = {17, 5};
Integer[] expected = {5, 17};
QuickSort.sort(a);
System.out.println(Arrays.toString(a));
Assert.assertArrayEquals(expected, a);
}
@Test
public void testSort3() {
Integer[] a = {64, 18, 74, 89, 58, 17, 48, 44, 92, 88, 78, 80, 75, 25, 77, 18, 39, 95, 11, 2};
Integer[] expected = {2, 11, 17, 18, 18, 25, 39, 44, 48, 58, 64, 74, 75, 77, 78, 80, 88, 89, 92, 95};
QuickSort.sort(a);
System.out.println(Arrays.toString(a));
Assert.assertArrayEquals(expected, a);
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!看来您需要学习使用调试器。请帮助自己一些complementary debugging techniques。如果您之后仍有问题,请随时回来提供更多详细信息。
-
为什么要迭代地实现 QuickSort,而依赖于 Stack 类呢?当您递归调用 QuickSort 时,它会隐式使用 Stack,但代码会更干净,并且可能比您的版本运行得稍快。如果这是某种学术练习,看看你是否能做到,那很酷。如果你这样做是因为你认为迭代总是比递归快,那是不正确的,你应该坚持使用递归。
-
@ScottK 因为这是一项学校作业,我假设(至少部分)意图是使隐式堆栈显式。
标签: java stack iteration quicksort non-recursive