0

I am trying to make an array sorter. But I get an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7

I don't know how to fix it. If I delete the line with the arrow then the code works, but then it doesn't swap. What did I do wrong?

Thanks for your help!

public class Main {

    public static void main(String[] args) {
        int[] list = {5, 3, 7, 2, 4, 8};

        for (int i = 0; i < list.length; i = i + 2) {
            if (i != list.length - 1) {

                if (list[i] > list[i + 1]) {

                    int leftNumber = list[i];
                    int rightNumber = list[i + 1];

                    int src = i;
                    int temp = list[i];

                    list[i] = list[i + 1];
                    //--> list[i + 1] = list[temp];

                    System.out.println(leftNumber + " : " + rightNumber);
                    System.out.println(i + " : " + (i + 1));

                    System.out.println(Arrays.toString(list));


                } else {
                    System.out.println("Good!");
                }
            }
        }


    }



}
tmucha
  • 689
  • 1
  • 4
  • 19
Bastiaan
  • 67
  • 1
  • 6

3 Answers3

2

temp is not an array index: you assigned it list[i], which is an array element.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
2

int temp = list[i]; and list[i + 1] = list[temp]; are the lines which cause the problem.

temp could be more than size of the list, how could you access list[temp], you may want to replace that with list[i+1] = temp

SomeDude
  • 13,876
  • 5
  • 21
  • 44
0

You problem is with list[temp];. Here it will crash when temp value is larger than your array size. You need to correct your code like below:-

list[i + 1] = leftNumber;
list[i ] = rightNumber;

It will still crash in the if condition hence change your for loop like below:

 for (int i = 0; i < (list.length - 1); i = i + 2)

As you are swapping the value here which you stored already hence no need for below lines of codes at all:-

/*
int src = i;
int temp = list[i];

list[i] = list[i + 1];
--> list[i + 1] = list[temp];
 */

All the above lines are useless.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17