QuickSort 永不停止
QuickSort never stops
我正在尝试实现快速排序算法,但是当我 运行 它永远不会停止,结果是 WhosebugException
。
(我知道像我一样用两个栈来重新排列数组,不是最高效的方式,但此时这不是那么重要了。)
private static void quickSort(int[] a, int start, int end) {
if (start >= end) {
return;
}
int pivot = a[start];
Stack<Integer> left = new Stack<Integer>();
Stack<Integer> right = new Stack<Integer>();
for (int i = start + 1; i <= end; i++) {
if (a[i] < pivot) {
left.push(a[i]);
} else {
right.push(a[i]);
}
}
int arrayIndex = 0;
int middle = 0;
while (left.size() > 0) {
a[arrayIndex++] = left.pop();
}
middle = arrayIndex;
a[arrayIndex++] = pivot;
while (right.size() > 0) {
a[arrayIndex++] = right.pop();
}
quickSort(a, start, middle - 1);
quickSort(a, middle + 1, end);
}
int arrayIndex = 0;
必须替换为
int arrayIndex = start;
我正在尝试实现快速排序算法,但是当我 运行 它永远不会停止,结果是 WhosebugException
。
(我知道像我一样用两个栈来重新排列数组,不是最高效的方式,但此时这不是那么重要了。)
private static void quickSort(int[] a, int start, int end) {
if (start >= end) {
return;
}
int pivot = a[start];
Stack<Integer> left = new Stack<Integer>();
Stack<Integer> right = new Stack<Integer>();
for (int i = start + 1; i <= end; i++) {
if (a[i] < pivot) {
left.push(a[i]);
} else {
right.push(a[i]);
}
}
int arrayIndex = 0;
int middle = 0;
while (left.size() > 0) {
a[arrayIndex++] = left.pop();
}
middle = arrayIndex;
a[arrayIndex++] = pivot;
while (right.size() > 0) {
a[arrayIndex++] = right.pop();
}
quickSort(a, start, middle - 1);
quickSort(a, middle + 1, end);
}
int arrayIndex = 0;
必须替换为
int arrayIndex = start;