交换排序-冒泡排序

什么是冒泡排序

什么是冒泡排序呢?具体请看如下图
image
image
image
image
image
经过总结出代码如下:

 public static void bubbleSort(int[] array) {
        //外层控制趟数
        for (int i = 0; i < array.length - 1; i++) {
            //内层控制比较次数
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j+1]) {
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {10,9,8,7,6,5,4,3,2,1};
        System.out.println("排序前:" + Arrays.toString(array));
        bubbleSort(array);
        System.out.println("排序后:" + Arrays.toString(array));
    }

结果:
image

冒泡排序的优化

请看这种特殊的情况:
image

posted on 2025-09-10 15:27  笨忠  阅读(5)  评论(0)    收藏  举报