Search code examples
javaarraysswap

How to switch two components in an array?


I was wondering how to switch the components in an array. My goal is to rearrange this array in numerical order, but when I try it keeps throwing up the exception "Index 22 out of bounds for length 9"

for (int i = 0; i < intArray.length - 1; i++) {
    for (int j = 1; j < intArray.length - 1; j++)
        if (intArray[j - 1] > intArray[j]) {
            swap(intArray[j - 1], intArray[j], intArray);
        }
    System.out.print(intArray[i]);
    System.out.print(" , ");
}
public static void swap(int a, int b, int[] arr) {
    int x = arr[a];
    arr[a] = arr[b];
    arr[b] = x;

}

Solution

  • Try passing in the indices instead of the values of the array

    i.e. Changing

    if (intArray[j-1] > intArray[j]){
        swap(intArray[j-1], intArray[j], intArray);
    }
    

    to

    if (intArray[j-1] > intArray[j]){
        swap(j-1, j, intArray);
    }
    

    Also your outermost loop runs 1 less than last element of intArray.

    You could use

    for (int i = 0; i < intArray.length; i++)
    

    instead