冒泡排序优化版

    public static void main(String[] args) {
        int[] arr = new int[]{0, 6, 4, 3, 2, 1, 9, 5, 7, 8};
        sort(arr);
        System.out.println("第一次: " + Arrays.toString(arr));

        arr = new int[]{6, 4, 3, 2, 1, 5, 0, 7, 8, 9};
        sort2(arr);
        System.out.println("第二次: " + Arrays.toString(arr));
    }
    
    ------------------------------------------------------------
    打印结果
    第一次: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    第二次: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    ------------------------------------------------------------

Process finished with exit code 0

    public static void sort(int[] nums) {
        boolean isSort = true;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    int a = nums[j + 1];
                    nums[j + 1] = nums[j];
                    nums[j] = a;
                    isSort = false;
                }
            }
            if (isSort) {
                break;
            }
        }
    }

    public static void sort2(int[] nums) {
        int lastChangeIndex = 0;
        int sortBorder = nums.length - 1;
        boolean isSort = true;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < sortBorder; j++) {
                if (nums[j] > nums[j + 1]) {
                    int a = nums[j + 1];
                    nums[j + 1] = nums[j];
                    nums[j] = a;
                    isSort = false;
                    lastChangeIndex = j;
                }
            }
            sortBorder = lastChangeIndex;
            if (isSort) {
                break;
            }
        }
    }
最后修改:2022 年 05 月 23 日
如果觉得我的文章对你有用,请点个赞吧~