【发布时间】:2013-10-27 02:32:53
【问题描述】:
我正在尝试在 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);
}
【问题讨论】:
-
不看你的代码,这听起来像是计算递归索引值的错误。在调试器中运行并确保您不会被卡住的索引对绊倒。
-
它说第36行有错误但它没有写也你没有写main方法
-
toIdx在调用quickSort中的作用是什么?递归排序的索引范围是多少? for循环中i的取值范围是多少?
标签: java algorithm stack-overflow quicksort