带栈的非递归Quicksort

时间:2014-11-24 17:41:59

标签: java stack quicksort

我正在尝试使用堆栈实现快速排序而不递归。 sort方法应该进行分区,并将子列表的边界存储为堆栈中的数组。然后,sort方法将循环返回并弹出其中一个子列表,并对其进行分区,然后再推回另外两个子列表。这应该继续,直到对整个字符串数组进行排序。

存储在堆栈中的数组由于某种原因而改变,即使我没有触及堆栈(据我所知)。这破坏了那种。

这是代码:

public static void qsort (String [] data)
    {               
    Stack stk = new Stack ();
    Integer mid;
    Integer [] bounds = new Integer [2];
    bounds [0] = 0;
    bounds [1] = data.length - 1;
    Integer [] rlist = new Integer [2];
    Integer [] llist = new Integer [2];
    while (!stk.isEmpty())
        {
        System.out.println ("----------");
        bounds = stk.pop();
        stk.print();
        System.out.println ("lb " + bounds[0].intValue() + " rb " + bounds [1].intValue());
        print (data);
        stk.print();

        llist[0] = bounds[0];
        System.out.println ("l0 " + llist[0].intValue()  + "  mid: " + mid.intValue() + "  b0 " + bounds[0].intValue() + "  b1 " + bounds[1].intValue());
        llist[1] = new Integer (mid.intValue()-1);
        System.out.println ("l0 " + llist[0].intValue() + "  l1 " + llist[1].intValue() + "  mid: " + mid.intValue() + "  b0 " + bounds[0].intValue() + "  b1 " + bounds[1].intValue());
        stk.print();
        rlist[0] = new Integer (mid.intValue()+1);
        System.out.println ("l0 " + llist[0].intValue() + "  l1 " + llist[1].intValue() + "  mid: " + mid.intValue() + "  r0 " + rlist[0].intValue());
        rlist[1] = bounds[1];
        System.out.println ("l0 " + llist[0].intValue() + "  l1 " + llist[1].intValue() + "  mid: " + mid.intValue() + "  r0 " + rlist[0].intValue() + " r1 " + rlist[1].intValue());

    if (rlist[1].intValue() > rlist[0].intValue()) 
        {
        stk.push (rlist);
        System.out.println ("pushed right");
        }
    if (llist[1].intValue() > llist[0].intValue()) 
        {
        stk.push (llist);
        System.out.println ("pushed left");
        }
    System.out.println("stksize "+stk.size);
    stk.print();
    }
}

我添加了一堆打印语句用于调试目的。对于给定的输入:

q
w
e
r
a
t

我得到了这个输出:

----------
---
---
lb 0 rb 5
a
e
q
r
w
t
---
---
l0 0  mid: 2  b0 0  b1 5
l0 0  l1 1  mid: 2  b0 0  b1 5
---
---
l0 0  l1 1  mid: 2  r0 3
l0 0  l1 1  mid: 2  r0 3 r1 5
pushed right
pushed left
stksize 2
---
l 0 r 1
l 3 r 5
---
----------
---
l 3 r 5
---
lb 0 rb 1
a
e
q
r
w
t
---
l 3 r 5
---
l0 0  mid: 0  b0 0  b1 1
l0 0  l1 -1  mid: 0  b0 0  b1 -1
---
l 3 r 5
---
l0 0  l1 -1  mid: 0  r0 1
l0 0  l1 -1  mid: 0  r0 1 r1 -1
stksize 1
---
l 1 r -1
---
----------
---
---
lb 1 rb -1
a
e
q
r
w
t
---
---
l0 1  mid: 1  b0 1  b1 -1
l0 1  l1 0  mid: 1  b0 1  b1 -1
---
---
l0 1  l1 0  mid: 1  r0 2
l0 1  l1 0  mid: 1  r0 2 r1 -1
stksize 0
---
---
a
e
q
r
w
t

我通过打印“--------”分隔每次迭代。请注意,存储在堆栈中的值正在被更改,我将重新分配无关变量的值。

0 个答案:

没有答案