如何在冒泡排序中修复 'java.lang.ArrayOutOfBound exception' in java

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

当我尝试 运行 这段冒泡排序代码时,出现异常 java.lang.ArrayOutOfBound。你能帮我解决这个异常吗?

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

在内循环中更改<= to <。您正在使用 i+1,它将超出上一次迭代中的索引。

for(int i=0;i<a.length-1;i++)
for(int i=0;i<=a.length-1;i++){
        if(a[i]>a[i+1])

你在使用 a[i+1] 时超出了数组的范围。 在您的代码中,您的索引上升到最后一个单元格。 更改您的 for 循环:

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