ArrayIndexOutOfBoundsException

morgens6

Neues Mitglied
Hallo,

wollte insertionSort üben, indem ich einen 1d. Array in der Methode sortiere und in einem 2d. Array die Zwischenschritte bis zum Ergebnis speichere. Leider klappt's bei der Ausgabe nicht ganz.

Java:
    public static void main(String[] args) {
        int t[] = {4, 1, 8, 9, 6, 5};
        int sortSteps[][] = insertionSort(t);
        for(int i = 0; i  < sortSteps.length; i++) {
            for(int j = 0; i < sortSteps.length; j++) {
                System.out.println(sortSteps[i][j]);
            }
        }
    }
  
    public static int [][] insertionSort(int [] a){
      
        if(a == null) return null;
        if(a.length == 0) return new int [0][0];
        int result [][] = new int [a.length] [a.length];
        result [0] = a.clone();
      
        for(int i = 1; i < a.length; i++) {
            int index = i;
            int value = a[i];
            while(index > 0 && a[index-1] > a[index]) {
                a[index] = a[index-1];
                a[index-1] = value;
                index--;
            }
            result[i] = a.clone();
        }
        return result;
    }
}

Ausgabe:
4
1
8
9Exception in thread "main"
6
5
java.lang.ArrayIndexOutOfBoundsException: 6 at test.test.main(test.java:10)

Ich verstehe die Fehlermeldung, nur sehe ich den Fehler leider nicht. Ich hoffe mir kann jemand auf die Sprünge helfen.

Grüße
 
Gut, habe jetzt den dummen Fehler selber entdeckt. Falls dieser Thread jemals irgendwen interessieren sollte:
In der 2. for-Schleife der Main-Methode habe ich ausversehen "i < sortSteps.length" statt "j < sortSteps.length" getippt.
 

Zurück
Oben