When the below method is run it throws an ArrayIndexOutOfBoundsException
at line 179, which is the if
statement in the nested loop.
I was thinking it had something to do with the index of j-1
. So I took the -1 out and just had j
in the brackets, but it threw the same exception at the first line of the swap. I've looked for bubble sort syntax and from what I can tell is I'm good. I'm close, I know. Any suggestions to fix this?
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i); j++){
if(array1[j-1] > array1[j]){
//swap
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}