简体   繁体   中英

I'm getting a java.lang.StackOverflowError in my quicksort

This is basicly a simple quicksort whiche uses arraylists but I can't find the reason why I get stuck in an endless recursion. In the end the only reslut I get is a stack overflow error.

 List<Integer> quicksort(List<Integer> toSort){

        if(toSort.size() > 1){
            List<Integer> left = new ArrayList<>();
            List<Integer> right = new ArrayList<>();
            for(int i=0;i<toSort.size();i++){
                if(toSort.get(i) < toSort.get(toSort.size()/2))
                    left.add(toSort.get(i));
                else
                    right.add(toSort.get(i));
            }

            toSort = quicksort(left);
            toSort.addAll(quicksort(right));
            return toSort;

        }else
            return toSort;
    }

Consider you have 2 elements in your toSort List (when it's first called), [2, 1] .

First, you create two List s, left and right .

You then populate these based on the 'pivot'. You use toSort.get(toSort.size() / 2); as the pivot. toSort.size() = 2, so toSort.get(1) = 1 (from the List above) in this case.

You then add the elements to different List s based on whether they are LESS THAN this value. So that means you end up with (after the for loop has completed):

left = [] , right = [2, 1] .

You then call quickSort on both of these List s again. Second time round, when calling toSort.addAll(quicksort(right)); you're back in the exact state as your first call, and so the above just happens again. Eventually this results in a stack overflow.


Your problem here is that you have mis-implemented the quicksort algorithm. I'd recommend reviewing the pseudo-code for the quicksort algorithm that you based your implementation from, and working through smaller steps of it at a time (and then asking for help when you identify the smallest step that you're misunderstanding).

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