[英]quicksort implementation bug java
What am I doing wrong in my quicksort implementation below: 我在以下我的快速排序实现中做错了什么:
public static void quicksort(int[] array, int start, int end) {
while (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
}
public static int partition(int[] array, int start, int end) {
int pivot = array[end];
int pIndex = start;
for (int i = start; i <= end - 1; i++) {
if (array[i] <= pivot) {
int tmp = array[pIndex]; // swap values
array[pIndex] = array[i];
array[i] = tmp;
pIndex++;
}
}
int tmpVal = array[pIndex];
array[pIndex] = pivot;
array[end] = tmpVal;
return pIndex;
}
When running this against the test case of an array {7, 5, 3, 6, 8, 1, 2, 4}, it rearranges the array into {1, 2, 3, 4, 8, 5, 7, 6} where it orders the left side of the array, but then enters what seems to be an infinite loop with the array of {1, 2} and never leaving that recursive call. 当针对数组{7,5,3,6,8,1,1,2,4}的测试用例运行它时,它会将数组重新排列为{1,2,3,4,8,5,7,6}在其中它对数组的左侧进行排序,但是随后进入{1,2}数组似乎是一个无限循环,并且永远不会离开该递归调用。 I've tried adding a base case of if the array.length is less than 2, then return;
我尝试添加一个基本情况,如果array.length小于2,则返回;否则,返回0。 but that makes no difference.
但这没什么区别。
Here's a link to my code . 这是我的代码的链接。
Anyone know what could be wrong? 有人知道怎么了吗?
Your loop 你的循环
for (int i = 0; i <= end - 1; i++) {
Within partition
should be 在
partition
区内应该是
for (int i = start; i <= end - 1; i++) {
With out this your pIndex can be outside of the range start
to end
and there for your recusive calls to quicksort will have the same parameters. 否则,您的pIndex可能会超出范围的
start
和end
,因此您对quicksort的回溯调用将具有相同的参数。
Another problem with your ideone code which is not shown above is 您的ideone代码的另一个问题(上面未显示)是
if (array.length < 2) { return; }
Within quicksort
you are not changing the length of your array so array.length
will always be 8. 在
quicksort
您不会更改数组的长度,因此array.length
始终为8。
A 3rd problem, and the one causing the infinite loop is 第三个问题,导致无限循环的是
while (start < end) {
within quicksort
you are not changing the values for start or end during this loop, so this loop will never exit. 在
quicksort
您不会在此循环中更改start或end的值,因此该循环永远不会退出。 see https://ideone.com/wY23C6 for a working example. 有关工作示例,请参见https://ideone.com/wY23C6 。
while (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
should be 应该
if (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.