簡體   English   中英

Quicksort分區

[英]Quicksort Partition

我正在嘗試理解和實現快速排序:因此,我一直在閱讀以下內容:

http://www.geeksforgeeks.org/iterative-quick-sort/

我不了解分區代碼。

/* A typical recursive implementation of quick sort */

/* This function takes last element as pivot, places the pivot element at its
   correct position in sorted array, and places all smaller (smaller than pivot)
   to left of pivot and all greater elements to right of pivot */
int partition (int arr[], int l, int h)
{
    int x = arr[h];
    int i = (l - 1);

    for (int j = l; j <= h- 1; j++)
    {
        if (arr[j] <= x)
        {
            i++;
            swap (&arr[i], &arr[j]);
        }
    }
    swap (&arr[i + 1], &arr[h]);
    return (i + 1);
}

/* A[] --> Array to be sorted, l  --> Starting index, h  --> Ending index */
void quickSort(int A[], int l, int h)
{
    if (l < h)
    {        
        int p = partition(A, l, h); /* Partitioning index */
        quickSort(A, l, p - 1);  
        quickSort(A, p + 1, h);
    }
}

所以可以說我有這個數組[3,8,7],因此它將最后一個元素作為樞軸。 那是7。

分區函數的第一步將是(對於l = 0和h = 2):

x = 7
i = -1

那么在循環中, arr[j] <= x將為真。 因為3 <=7。所以它將i加1,然后將3與3交換? 這沒有意義。 那只會返回相同的數組

讓我們看看發生了什么:

x = 7
j = 0:

  3 <= 7: swap(arr[0], arr[0]) => nothing happens

j = 1:

  8 <= 7 is false => nothing happens

現在,請注意i == 0 ,我們有一行:

swap (&arr[i + 1], &arr[h]);

這意味着我們將arr[1]arr[2]交換,您的數組將為3 7 8 您在分析中沒有考慮這條線。

這是正確的,並且樞軸的返回位置i + 1 == 1也是正確的。

您可以在每個感興趣的行之后添加打印語句,也可以通過調試器逐步了解情況。 在紙上進行此操作可能會導致這樣的錯誤,您會意外地跳過一些步驟,尤其是在學習某些東西時(老實說,我花了幾分鍾才意識到您錯過了那條線)。

暫無
暫無

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

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