快速排序的递归参数

时间:2013-05-11 10:39:58

标签: java recursion double quicksort

我正在尝试实现一个简单的Quicksort算法(Doubly Linked List,循环)。算法工作得很好,但由于以下操作,它太慢了:     iEl = getListElement(l);     jEl = getListElement(r); 在非常长的输入列表中,我必须经常浏览整个列表,找到iEljEl,这是超慢的。

解决方案是(我认为)将这两个元素作为参数传递给分区函数。问题是,我找不到正确的元素。我试图输出很多可能性,但它们只是不合适。

以下是代码:

public void partition(int l, int r, ListElement lEl, ListElement rEl) {
    if (r > l) {
        ListElement p, iEl, jEl;
        int i, j, x;
        i = l;
        j = r;

        // These two lines are very slow with long input-lists
        // If I had the two correct parameters lEL and rEl, this would be much faster
        iEl = getListElement(l);
        jEl = getListElement(r);
        // getListElement walks through x-elements (l and r) of the list and then returns the element on that position 

        // If I had the correct Elements rEl and lEl, I could directly use these Elements, instead of going all the way through the list. Something like this:
        // iEl = lEl;
        // jEl = rEl;


        x = (int) Math.floor((j + i) / 2);
        p = getListElement(x);


        while (i <= j) {

            while (iEl.getKey() < p.getKey() && i < r) {
                i++;
                iEl = iEl.next;
            }

            while (jEl.getKey() > p.getKey() && j > l) {
                j--;
                jEl = jEl.prev;
            }

            if (i <= j) {
                if (iEl != jEl) {
                    swap(iEl, jEl);
                }
                ++i;
                --j;
                break;
            }
        }

        if (l < j) {
            // Here I need the two correct parameters
            partition(l, j, ???, ???);
        }

        if (i < r) {
            // Here I need the two correct parameters
            partition(l, j, ???, ???);
        }
    }
}

该函数以:partition(0,numOfElements - 1,list.first,list.first.prev)开始;

我为这两个参数尝试了几个变体(iEl,iEl.prev,jEl,jEl.next,...),但似乎没有一个适合。

正如我所说,该功能有效,但速度很慢。通过传递这两个参数,这是否可以加速功能?如果是这样,我必须使用哪些参数?

1 个答案:

答案 0 :(得分:1)

我不知道“元素作为参数”会有多大帮助。问题是必须走列表来获取元素,不是吗?

为什么不在排序期间从列表中删除数组?遍历列表一次,对数组中的每个元素进行引用,然后执行我认为的更正常的快速分区,将数组分区并将元素移动到那里。当然,当您移动数组中的元素时,您还必须重新排列其下一个/上一个指针,以便在完成后链接列表完好无损,但无论如何您必须这样做。这将节省您走在列表中以获取元素。完成后只需丢弃数组(或ArrayList)。