简体   繁体   中英

StackOverflowError while implementing QuickSort

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM