简体   繁体   English

如何使用固定枢轴将迭代快速排序更改为使用随机数据块的迭代快速排序?

[英]How do I change iterative quicksort with fixed pivot to iterative quicksort with random pivot?

I found this code for quicksort with a fixed pivot. 我发现这个代码用于带有固定枢轴的快速排序。 It always takes a right-hand side element of the given table as a pivot. 它总是将给定表的右侧元素作为一个轴。 I want it to take a random element as a pivot. 我希望它将随机元素作为一个支点。 I think that x is a pivot here, so I thought it was a good idea to change it to a random element from a given list, but it turns out that it is not working. 我认为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;
        }
    }
}

I tried changing lines 我尝试换线

int x = arr[h];

and

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

to

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

and then 接着

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

but it is not sorting properly. 但它没有正确排序。 Obviously I'm doing something wrong here. 显然我在这里做错了。 Please help. 请帮忙。

Your partition function assumes the pivot is at the end of the partition. 您的分区函数假定数据透视表位于分区的末尾。 Consider moving your random pivot to the end of the partition first. 考虑首先将随机数据移动到分区的末尾。

ie add 即添加

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

after choosing your pivot. 选择你的支点后。

The problem is that the 'partition' function now moves the pivot so it doesn't remain at the r index. 问题是'partition'函数现在移动了pivot,所以它不会保留在r索引处。 And the function also misses the last element (at index h ). 并且该函数也会错过最后一个元素(在索引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]); 最简单的解决方案是在选择它之后将枢轴放在最右边的位置,并保持其他一切相同:put swap(&arr[r], &arr[h]); before the first loop in partition() , and restore the last swap to swap (&arr[i + 1], &arr[h]); partition()的第一个循环之前,将最后一个交换恢复为swap (&arr[i + 1], &arr[h]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM