0

I am getting an exception java.lang.ArrayOutOfBound when i am trying to run this code of bubble sort. Can you please help me solve this exception.

public class bubblesort {
    public static void main(String args[]) {
        int[] a = {30, 20, 7, -9, 0, 3, 122};
        int temp = 0;
        for (int b = a.length - 1; b > 0; b--) {
            for (int i = 0; i <= a.length - 1; i++) {
                if (a[i] > a[i + 1])
                    swap(a, i, i + 1);

            }
        }
        for (int c = 0; c <= a.length - 1; c++) {
            System.out.println(a[c]);
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int temp;
        if (i == j) {
            return;
        }
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
uli
  • 641
  • 5
  • 15
abcd
  • 35
  • 2

2 Answers2

0

Change <= to < in the inner loop. You are using i+1 which will go beyond the index in the last iteration.

for(int i=0;i<a.length-1;i++)
Prakash Krishna
  • 1,031
  • 3
  • 12
0
for(int i=0;i<=a.length-1;i++){
        if(a[i]>a[i+1])

your going out of your array's bounds when your using a[i+1]. in your code your index goes up until the last cell. change your for loop:

 for(int i=0;i<a.length-1;i++){
NirF
  • 197
  • 5