我正在尝试在 ArrayList 上实现快速排序算法。但是,我得到一个
Exception in thread "main" java.lang.StackOverflowError
at sorting.QuickSort.quickSort(QuickSort.java:25)
at sorting.QuickSort.quickSort(QuickSort.java:36)
at sorting.QuickSort.quickSort(QuickSort.java:36)
at sorting.QuickSort.quickSort(QuickSort.java:36)
at sorting.QuickSort.quickSort(QuickSort.java:36)
...
我不确定为什么会有溢出。下面是我的实现:
public static void quickSort(ArrayList<Integer> al, int fromIdx, int toIdx) {
int pivot, pivotIdx;
if (fromIdx < toIdx) {
pivot = al.get(fromIdx);
pivotIdx = fromIdx;
for (int i = 0; i != (fromIdx + 1); i++) {
if (al.get(i) <= pivot) {
pivotIdx += 1;
swap(al, pivotIdx, i);
}
}
swap(al, fromIdx, pivotIdx);
quickSort(al, fromIdx, pivotIdx - 1);
quickSort(al, pivotIdx + 1, toIdx);
}
}
public static void swap(ArrayList<Integer> al, int xIdx, int yIdx) {
Integer temp = al.get(xIdx);
al.set(xIdx, al.get(yIdx));
al.set(yIdx, temp);
}