1

我发现此代码用于具有固定枢轴的快速排序。它总是将给定表格的右侧元素作为枢轴。我希望它以随机元素为轴心。我认为这x是一个支点,所以我认为将其更改为给定列表中的随机元素是个好主意,但事实证明它不起作用。

void swap ( int* a, int* b )
{
    int t = *a;
    *a = *b;
    *b = t;
}


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);
}

void quickSortIterative (int arr[], int l, int h)
{
    int stack[ h - l + 1 ]; 
    int top = -1;

    stack[ ++top ] = l;
    stack[ ++top ] = h;

    while ( top >= 0 )
    {
        h = stack[ top-- ];
        l = stack[ top-- ];

        int p = partition( arr, l, h );

        if ( p-1 > l )
        {
            stack[ ++top ] = l;
            stack[ ++top ] = p - 1;
        } 
        if ( p+1 < h )
        {
            stack[ ++top ] = p + 1;
            stack[ ++top ] = h;
        }
    }
}

我尝试换行

int x = arr[h];

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

int r = l+rand()%(h-l);
int x = arr[r];

进而

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

但它没有正确排序。显然我在这里做错了什么。请帮忙。

4

2 回答 2

2

您的分区函数假定枢轴位于分区的末尾。考虑首先将您的随机枢轴移动到分区的末尾。

即添加

swap(&arr[r], &arr[h]);

选择您的支点后。

于 2013-03-20T06:03:05.523 回答
2

The problem is that the 'partition' function now moves the pivot so it doesn't remain at the r index. And the function also misses the last element (at index h). The simplest solution would be to place the pivot to the right-most position just after selecting it, and remain everything other the same: put swap(&arr[r], &arr[h]); before the first loop in partition(), and restore the last swap to swap (&arr[i + 1], &arr[h]);

于 2013-03-20T06:05:41.550 回答