簡體   English   中英

快速排序的遞歸參數

[英]Recursive parameters for quicksort

我正在嘗試實現一個簡單的Quicksort算法(雙向鏈表,循環)。 該算法效果很好,但是由於以下操作,它太慢了: 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等),但似乎沒有一個合適的選擇。

如我所說,該功能有效,但速度很慢。 通過傳遞這兩個參數甚至可以加速功能嗎? 如果是這樣,我必須使用哪些參數?

我不認為“元素作為參數”將有多大幫助。 問題在於必須遍歷列表才能獲取元素,不是嗎?

為什么不在排序過程中將數組從列表中刪除呢? 遍歷列表一次,對數組中的每個元素進行引用,然后執行我認為更常規的快速排序,即對數組進行分區並在其中移動元素。 當然,當您在數組中移動元素時,還必須重新排列其下一個/上一個指針,以使鏈接列表在完成后保持完整,但是無論如何都必須這樣做。 這將使您免去遍歷列表獲取元素的麻煩。 完成后就丟棄該數組(或ArrayList)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM