我正在尝试实施快速排序算法,但是当我运行时,它永远不会停止,导致StackOverflowException
。
(我知道使用两个堆栈来重新排列数组,就像我一样,这不是最有效的方法,但此时这并不是那么重要。)
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);
}
答案 0 :(得分:2)
int arrayIndex = 0;
必须替换为
int arrayIndex = start;