随机Hoare分区 - 某些索引上的错误分区

时间:2015-04-06 16:37:38

标签: java algorithm

我确实尝试了所有方法,尝试了所有解决方案,但它仍然无效。好像Hoare分区只在某些情况下有效,但偶尔我甚至不理解它在做什么。 是的,我知道算法是如何工作的,但是实现明智吗?我会说实话,我不知道它是如何尝试分区的。所以,这是我的测试数组:

2, 30, 1, 99, 46, 33, 48, 67, 23, 76

我首先尝试实现经典算法:

private int hoarePartition(int l, int r) {
    int pivot = array[l];
    while (true) {
        int i = l - 1, j = r + 1;
        do {
            --j;
        } while (array[j] > pivot);

        do {
            ++i;
        } while (array[i] < pivot);

        if (i < j) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        } else {
            System.out.println(Arrays.toString(array));
            return j;
        }
    }
}

private int randomizedPartition(int l, int r) {
    int pivot = generator.nextInt(r - l + 1);

    int temp = array[l];
    array[l] = array[pivot];
    array[pivot] = temp;

    return hoarePartition(l, r);
}

Test cases: [2, 30, 1, 99, 46, 33, 48, 67, 23, 76]

Random Pivot | Partitioned Array                      | Status
0 - [  2 ]     [1, 2, 30, 99, 46, 33, 48, 67, 23, 76]   OK
1 - [ 30 ]     [23, 2, 1, 30, 46, 33, 48, 67, 99, 76]   OK
2 - [  1 ]     [1, 30, 2, 99, 46, 33, 48, 67, 23, 76]   OK
3 - [ 99 ]     [76, 30, 1, 2, 46, 33, 48, 67, 23, 99]   OK
4 - [ 46 ]     [23, 30, 1, 33, 2, 46, 48, 67, 99, 76]   OK
5 - [ 33 ]     [23, 30, 1, 2, 33, 46, 48, 67, 99, 76]   OK
6 - [ 48 ]     [23, 30, 1, 2, 46, 33, 48, 67, 99, 76]   OK
7 - [ 67 ]     [23, 30, 1, 2, 46, 33, 48, 67, 99, 76]   OK
8 - [ 23 ]     [2, 1, 23, 99, 46, 33, 48, 67, 30, 76]   OK
9 - [ 76 ]     [2, 30, 1, 23, 46, 33, 48, 67, 76, 99]   OK

随机枢轴选择应该是(r - l + 1)。通过这种修改,它终于有效了。

1 个答案:

答案 0 :(得分:0)

你生成一个不必在[p,q]中的数字:

int i = (p + generator.nextInt(q)) % (q - p);

生成的数字i位于[0,q-p]范围内,这显然是错误的,例如在p=6,q=10

您正在寻找的是:

int i = (p + generator.nextInt(q-p+1)); //assuming q>p here

这会在[p+0,p+q-p] = [p,q]

中生成一个随机数

作为旁注,使用l,r代替p,q会稍微更具可读性,并尝试对命名变量保持一致(两种方法中的q / r具有相同的作用,没有理由两个不同的名字)

相关问题