BubbleSort StackOverflowError

arraylist, java, sorting, stack-overflow

Solution

That happens when two consecutive clouds have the same speed.

cl1.getSpeed() < cl2.getSpeed()

is false, so the clouds get swapped and `sort` is called again. In that call,

cl1.getSpeed() < cl2.getSpeed()

is still false, so you swap again and call `sort`. This goes on forever (or better: till the stack is full).

Change `<` to `<=` and everything should work fine.

Problem

I added this recursive BubbleSort algorithm to my game which runs on lwjgl. I'm trying to sort an ArrayList of "Cloud" objects by a float which is the speed of this cloud. For some reason sometimes I get a "java.lang.StackOverflowError" at the line I invoke the method in itself. Here's the code: ``` public void sort() { for (int i = 0; i < clouds.size() - 1; i++) { Cloud cl1 = clouds.get(i); Cloud cl2 = clouds.get(i + 1); if (cl1.getSpeed() < cl2.getSpeed()) { continue; } clouds.set(i, cl2); clouds.set(i+1, cl1); this.sort(); } } ``` And here are the errors I'm getting: ``` Sat May 04 20:28:45 CEST 2013 ERROR:null java.lang.StackOverflowError at backgrounds.Clouds.sort(Clouds.java:224) [...] // The line above is repeated for some hundred times. ```

Original source