就地分区返回枢轴位置

时间:2012-02-06 14:10:01

标签: algorithm pivot quicksort divide-and-conquer data-partitioning

由于普通分区返回索引j,使得索引i <= j的每个元素小于choisen pivot,并且每个元素的索引为m&gt; j比枢轴大,不能保证j是枢轴。是否有可能创建另一个就地分区算法,它准确地返回新的枢轴位置? 最初,我试图在最后一个位置移动choisen枢轴,但它不会导致最佳解决方案。

1 个答案:

答案 0 :(得分: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;
}