簡體   English   中英

當使用兩個不同的鍵快速分配N個項目的數組時,什么是最大函數調用堆棧大小

[英]What's Max function-call stack size when quicksorting an array of N items with only two distinct keys

實際上,這是來自Coursera的普林斯頓塞奇威克算法的一個問題。 我認為這是~log2(N)。 但是我運行實驗,當0.5N 1s 0.5N 0s互換時,它是~2ln(N),當N個不同的鍵時,它是〜2log2(N),為什么呢?

以下是Robert Sedgewick的第4版算法中的代碼:

public class Quick 
{ 
    public static void sort(Comparable[] a)
    { 
        StdRandom.shuffle(a);  // Eliminate dependence on input.
        sort(a, 0, a.length - 1);
    }

    private static void sort(Comparable[] a, int lo, int hi)
    {
        if (hi <= lo) return;
        int j = partition(a, lo, hi); // Partition (see page 291).
        sort(a, lo, j-1);  // Sort left part a[lo .. j-1].
        sort(a, j+1, hi);  // Sort right part a[j+1 .. hi].
    }

    private static int partition(Comparable[] a, int lo, int hi) 
    { // Partition into a[lo..i-1], a[i], a[i+1..hi]. 
        int i = lo, j = hi+1;  // left and right scan indices
        Comparable v = a[lo];  // partitioning item
        while (true)
        {  // Scan right, scan left, check for scan complete, and exchange. 
            while (less(a[++i], v)) if (i == hi) break;
            while (less(v, a[--j])) if (j == lo) break;
            if (i >= j) break;
            exch(a, i, j);
        }
        exch(a, lo, j);  // Put v = a[j] into position 
        return j;  // with a[lo..j-1] <= a[j] <= a[j+1..hi]. 
    }
}

如果你用Big O Notation分析它仍然是O(N ^ 2)但是如果你試圖找到它的平均復雜度,它可能是〜2log2(N)和AFAIK,有點難以找到算法的平均復雜度。

暫無
暫無

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

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