Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BubbleSort StackOverflowError

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.
like image 587
Deconimus Avatar asked May 04 '13 18:05

Deconimus


2 Answers

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.

like image 93
Vincent van der Weele Avatar answered Sep 28 '22 01:09

Vincent van der Weele


You comparison logic should skip two cloud objects if they are same too -

Change if to -

if (cl1.getSpeed() <= cl2.getSpeed()) {
    continue;
}
like image 21
devang Avatar answered Sep 28 '22 01:09

devang