【发布时间】:2018-05-27 06:43:44
【问题描述】:
试图弄清楚为什么 Hoare 分区算法总是将一个数组分成两个正确的部分。在下面的代码中,我扩展了 Hoare algorithm 以使我更清楚(请参阅 cmets 了解详细信息)
int partition(int[] arr, int leftIndex, int rightIndex) {
int pivot = arr[(leftIndex + rightIndex) / 2];
while (leftIndex <= rightIndex) {
while (arr[leftIndex] < pivot) leftIndex++;
while (arr[rightIndex] > pivot) rightIndex--;
// If all numbers at right places, than leftIndex and rightIndex
// could point at same array element index
// So it's means partion done.
// We should return leftIndex + 1 cause
// rightIndex points at the last element of the left sub array
if (leftIndex == rightIndex) return leftIndex + 1;
if (leftIndex < rightIndex) {
swap(arr, leftIndex, rightIndex);
leftIndex++;
rightIndex--;
}
}
//But here the tricky thing: Why does this "if case" never execute?
if (leftIndex - 1 > rightIndex)
System.out.println("leftIndex - 1 > rightIndex");
return leftIndex;
}
所以问题是:是否可以将数组传递给分区函数,所以下面的行会被执行?
if (leftIndex - 1 > rightIndex)
System.out.println("leftIndex - 1 > rightIndex");?
【问题讨论】:
标签: java algorithm quicksort partition