簡體   English   中英

對於快速排序的這種特定實現,最好的、平均的和最壞的情況是什么?

[英]What is the best, average and worst case for this specific implementation of Quick Sort?

我知道最好的平均時間是 O(n log(n)),最壞的時間是 O(n^2)。 誰能告訴我這些情況何時在這個特定的實現中真正發生? 它與其他實現有何不同?

    private void quickSort(int low, int high) {
        int i = low, j = high;
        // Get the pivot element from the middle of the list
        int pivot = array[low + (high - low) / 2];

        // Divide into two lists
        while (i <= j) {
            // If the current value from the left list is smaller then the pivot
            // element then get the next element from the left list
            while (array[i] < pivot) {
                i++;
            }
            // If the current value from the right list is larger then the pivot
            // element then get the next element from the right list
            while (array[j] > pivot) {
                j--;
            }

            // If we have found a values in the left list which is larger then
            // the pivot element and if we have found a value in the right list
            // which is smaller then the pivot element then we exchange the
            // values.
            // As we are done we can increase i and j
            if (i <= j) {
                swap(array, i, j);
                i++;
                j--;
            }
        }
        // Recursion
        if (low < j)
            quickSort(low, j);
        if (i < high)
            quickSort(i, high);
    }

任何反饋都受到高度贊賞。

最壞的情況發生在您選擇一個樞軸時,在“分為兩個列表”部分之后,最終位於數組的一個極端(最左側或最右側)。 原因是:兩個遞歸調用中的一個幾乎不會任何工作,而另一個會再次完成幾乎所有的工作

例如:你有一個從 1 到 100 的數字排列,你在中間選擇了一個支點。 假設樞軸為 1。您運行“分為兩個列表”部分,現在您必須對左側的 0 個元素和右側的 99 個元素進行排序。


最好的情況發生在主元將兩個列表分成兩半時(在置換示例中,當您選擇一個大約為 50 的主元時)。

暫無
暫無

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

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