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.
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.
You comparison logic should skip two cloud objects if they are same too -
Change if to -
if (cl1.getSpeed() <= cl2.getSpeed()) {
continue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With