【发布时间】:2015-04-07 01:43:02
【问题描述】:
我确实尝试了所有方法,尝试了所有解决方案,但仍然无法正常工作。似乎 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)。有了这个修改,它终于可以工作了。
【问题讨论】:
-
p 代表枢轴,r 代表什么?你是如何选择支点的?
-
我修改了代码,使其更具可读性。