为什么我的冒泡排序算法实现对整个数组进行排序并跳过第一个索引?

Why is my bubble sort algorithm implementation sorting the entire array and skips the first index?

public static int[] bubbleSort(int[] inputArray){

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

            int tempa = inputArray[i];
            int tempb = inputArray[i + 1];

            if(inputArray[i] > inputArray[i + 1]){
                inputArray[i] = tempb;
                inputArray[i + 1] = tempa;
                i = 0;
                System.out.println(Arrays.toString(inputArray));
            }
        }
        return inputArray;
}

此实现需要 [20, 35, -15, 7, 55, 1, -22] 和 returns [20, -22, -15, 1, 7, 35, 55]。对除第一个索引以外的所有内容进行排序。

Why ... skips the first index?

因为您在循环内设置了 i = 0,但随后循环将执行 i++,因此仅在第一次迭代时检查第一个元素,而不在任何 "restart" 上检查。

要正确重启,请使用 i = -1,这样 i++ 将使重启发生在 i = 0,而不是 i = 1

这将使代码工作,但在交换两个元素后立即重新启动效率低下,因为您将反复检查数组的开头。