这让我发疯了,我知道这是导致这种情况的一些一次性错误,但由于某种原因,我的分区功能没有正确分区。我做错了什么?
public static int partition(int numbers[], int lhs, int rhs) {
int pivot = numbers[(rhs - lhs) / 2];
int lIndex = lhs - 1;
int rIndex = rhs + 1;
while (true) {
while (numbers[++lIndex] < pivot);
while (numbers[--rIndex] > pivot);
if (lIndex > rIndex) break;
int temp = numbers[lIndex];
numbers[lIndex] = numbers[rIndex];
numbers[rIndex] = temp;
}
return lIndex;
}
答案 0 :(得分:2)
最好找到枢轴(在您的情况下为中点):
int pivot = numbers[lhs + (rhs - lhs) / 2];
如果lhs和rhs足够高,它会阻止lhs + rhs导致整数溢出。
答案 1 :(得分:1)
这是一个问题:
int pivot = numbers[(rhs - lhs) / 2];
假设lhs
= 100且rhs
= 120.上面将选择元素(120 - 100)/ 2 = 10作为支点!
我想你想要像
这样的东西int pivot = numbers[(rhs + lhs) / 2];
至少会在您尝试分区的范围内选择一个支点!