迭代的Quicksort

时间:2017-03-12 22:34:22

标签: java stack iteration quicksort non-recursive

我试图实现一个迭代运行的快速排序方法。我用堆栈来保存信息。它还将使用分区来实现这一目标。我知道底部代码的分区部分很好,它只是第一个遇到问题的块。出于某种原因,我的代码并没有按照它的设想做。对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);
}


}

1 个答案:

答案 0 :(得分:0)

因为在partition()中hi是数组最后一个元素的索引,所以在代码的最初部分,第二次推送应该是push(a.length-1),{{1索引而不是last索引。 if也应检查hi-lo&lt; 1。

调用分区后,j =现在排序的数据透视表的索引。应删除j = hi + ...的行,因为partition()返回要用于j的值。由于[j]被排序,因此不应将其包括在要递归处理的两个分区中。需要修复两个stack.push(j ...)行。