0

由於正常分區返回索引j,因此索引爲i的每個元素< = j小於choisen主元,並且索引爲m> j的每個元素都大於主元,沒有保證j是關鍵。是否有可能創建另一個就地分區算法,該算法返回新的樞軸位置? 最初,我希望將choisen樞軸放在最後的位置,但它並不會導致最佳的解決方案。返回Pivot位置的分區

+0

'有沒有保證,j是樞軸'Counterexample請嗎?我的意思是,(如果我理解你的問題是正確的),你可以製作一個數字和數據透視表,這樣分區並不能給出正確的位置。 – Ishtar 2012-02-06 14:27:26

+0

讓我們定義A = {5,3,2,6,4,1,3,7},並讓它成爲數據透視表5,執行分區,輸出這個{3,3,2,1,4,6, 5,7},jd是4的索引。 – gr1ph00n 2012-02-06 14:51:02

+1

你的例子看起來不對。如果樞軸點數爲5,則只剩下小於5的數字,並且只有大於5的數字應該在其右側(而5應該在中間)。 – synepis 2012-02-06 16:04:43

回答

1

關鍵是保持樞軸脫離交換,除非在開始時將其存儲在一個邊界處,並在最後將其交換到正確的位置時結束。

int partition(int *A, int low, int high) { 

    if (high <= low) return low; // in that case, partition shouldn't be called, but cater for it 

    int pivot_position = low; // or high, or low + (high-low)/2, or whatever 
    int pivot = A[pivot_position]; 

    A[pivot_position] = A[high]; 
    A[high] = pivot; // these two lines are unnecessary if pivot_position == high 
    int i = low, j = high-1; 

    while(i < j) { 

     while(i < j && A[i] <= pivot) 
      ++i; // i == j or A[i] > pivot, and A[k] <=pivot for low <= k < i 

     while(i < j && A[j] > pivot) 
      --j; // i == j or A[j] <= pivot, and A[m] > pivot for j < m < high 

     if (i < j) { 
      int temp = A[j]; 
      A[j] = A[i]; 
      A[i] = temp; 
     } 
    } 
    if (A[i] <= pivot) 
     ++i; 

    // now A[k] <= pivot for low <= k < i and A[m] > pivot for i <= m < high 
    A[high] = A[i]; 
    A[i] = pivot; 
    return i; 
} 
+0

很酷,謝謝,它的工作原理,所以我最初的想法是確定的,但我確實錯過了只在Array [1..n-1]上執行分區的部分,並且使用比它大的第一個元素交換pivot。再次感謝 :) – gr1ph00n 2012-02-07 15:24:40