Search code examples
javadata-structuresbubble-sort

How to fix 'java.lang.ArrayOutOfBound exception' in java in Bubble-sort


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;
    }
}

Solution

  • 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++){