BubbleSort StackOverflowError

时间:2013-05-04 18:48:11

标签: java sorting arraylist stack-overflow

我将这个递归的BubbleSort算法添加到我在lwjgl上运行的游戏中。我正在尝试通过浮点数对“云”对象的ArrayList进行排序,这就是这个云的速度。

出于某种原因,有时我会在我调用该方法的行中得到一个“java.lang.StackOverflowError”。

以下是代码:

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

以下是我得到的错误:

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.

5 个答案:

答案 0 :(得分:9)

当两个连续的云具有相同的速度时会发生这种情况。

cl1.getSpeed() < cl2.getSpeed()

为false,因此交换云并再次调用sort。在那次电话会议中,

cl1.getSpeed() < cl2.getSpeed()

仍为false,因此您再次交换并致电sort。这种情况会持续下去(或更好:直到堆栈已满)。

<更改为<=,一切正常。

答案 1 :(得分:6)

你的比较逻辑应该跳过两个云对象 - 如果它们是相同的 -

更改为 -

if (cl1.getSpeed() <= cl2.getSpeed()) {
    continue;
}

答案 2 :(得分:4)

对于java Arrays.sort()中的数组使用内置的排序方法可能更好,您只需要覆盖compare to方法即可。这是它的外观。

@Override
public int compareTo(Book other) {
//compare logic here
}

您还必须实现Comparable才能执行此操作

答案 3 :(得分:0)

可以进一步优化

public void sort() {
    boolean swaps = false;
    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;
        }
        swaps = true;
        clouds.set(i, cl2);
        clouds.set(i+1, cl1);
    }

    //Re-Iterate all the elements only if a swap is found
    if( swaps )
      this.sort();
}

答案 4 :(得分:0)

堆栈溢出的常见原因是一个错误的递归调用,这是在递归函数没有正确的终止条件时引起的,所以它最终会自动调用它。在您的情况下,由于严格的'&lt;'而不满足终止条件签名所以你必须将其更改为“&lt; =”就是这样。

相关问题