Not the same bubble sort, easy to understand

public class BubbleSortVersion6 {

    public static void bubbleSort(int[] arr){
        // 默认未排好序
        boolean sort = false;
        // 循环次数 每次确定的最值元素的位置
        int lastIndex = arr.length-1;
        // 进入while循环
        while (!sort) {
            // 进入while循环,假设已经排好序
            sort = true;
            for (int i = 0; i < lastIndex; i++) {
                // 如果发生过交换,则是未排好序
                if (arr[i] > arr[i + 1]) {
                    swap(arr, i, i + 1);
                    sort = false;
                }
            }
            lastIndex--;
        }
    }

    private static void swap(int[] arr, int x, int y) {
        int current = arr[x];
        arr[x] = arr[y];
        arr[y] = current;
    }

    public static void main(String[] args) {
        int[] arr = {3,1,44,233,52,521,423,45};
        BubbleSortVersion6.bubbleSort(arr);
        System.out.println(Arrays.toString(arr));

    }
}

 

Published 16 original articles · won praise 4 · Views 1090

Guess you like

Origin blog.csdn.net/qq_41895761/article/details/104447616