StackOverflowError while implementing QuickSort

烂漫一生 提交于 2019-12-25 09:29:46

问题


I am trying to implement an QuickSort algorithm on an ArrayList. However, I am getting a

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)
    ...

I am not sure as to why is there an overflow. Below is my implementation:

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);
}

回答1:


If you're trying to sort the chunk of the array from fromIdx to toIdx, you should never look at element 0 unless it is in that chunk. But your implementation does.

Your indexing trick in the middle is also kind of..odd. I highly recommend that you do the exercise of cutting out little pieces of paper for the array, and writing tracking information on a sheet of paper so that you can trace through the algorithm. If when you physically do it, you see it not make sense, then it doesn't make sense in the computer either. And the act of holding physical pieces of paper may seem silly, but is of great help in visualizing exactly what you are doing. (The more precisely you can visualize what your code actually does, the more likely you are to be able to figure out if it is doing something wrong.)



来源:https://stackoverflow.com/questions/19614036/stackoverflowerror-while-implementing-quicksort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!