不一样的冒泡排序,通俗易懂

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

    }
}
发布了16 篇原创文章 · 获赞 4 · 访问量 1090

猜你喜欢

转载自blog.csdn.net/qq_41895761/article/details/104447616