我一直试图找出为什么代码不断给我一个arrayIndexOutOfBoundsException的原因。经过绝望的尝试,我在while循环中反转了2个布尔条件,程序运行正常。这确实让我感到困惑的原因是,这两个条件由应互换的AND子句分隔。

这是有问题的while语句:

while(compareIndex>=0 && key<data[compareIndex])//works
while(key<data[compareIndex] && compareIndex>=0) //Crashes


对于某些上下文,这里是方法主体的其余部分:

public static void insertionSort(int[] data){
    for(int i = 0; i<data.length; i++){
        int key = data[i];
        int compareIndex = i-1;
        while(key<data[compareIndex] && compareIndex>=0){
            data[compareIndex+1] = data[compareIndex];
            compareIndex--;
        }
        data[compareIndex+1] = key;
    }

}

最佳答案

int compareIndex = i-1; // <-- on the first iteration i = 0, and i-1 = -1
while(key<data[compareIndex] && compareIndex>=0)


你不能用-1索引数组

边注:
您应该在IDE中开发代码,然后在调试器中逐步进行。如果您不这样做,编程将变得更加困难。现在花时间学习如何做,您将成为一个更好的程序员。尝试IntelliJEclipse,它们是免费的。用Google搜索一下调试器中的代码。

10-08 03:13