首页 > 其他分享 >冒泡排序

冒泡排序

时间:2022-11-01 19:25:52浏览次数:54  
标签:int 冒泡排序 runningFlag static 66 array public

public class BubblingSort {
    public static void swap(int[] array, int i, int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    /**排序*/
    public static void bubblingSort(int[] array) {
        //首先考虑边界条件
        if(array == null || array.length < 2) {
            return;
        }
        boolean runningFlag = true;  //判断是否结束外层循环
        for (int i = 0;runningFlag && i < array.length; i++) {
            runningFlag = false;
            for (int j = 1; j < array.length - i; j++) {
                if(array[j-1] > array[j]) {
                    swap(array,j-1,j);
                    runningFlag = true; //存在交换,说明还没排完
                }
            }
        }
    }
    public static void main(String[] args) {
        //给定一个数组
        int[] array = {5,7,1,3,23,22,53,21,4,66,68,124,8};
        PrintUtil.printIntArray(array);  //5 7 1 3 23 22 53 21 4 66 68 124 8
        bubblingSort(array);
        PrintUtil.printIntArray(array);  //1 3 4 5 7 8 21 22 23 53 66 68 124
    }
}

标签:int,冒泡排序,runningFlag,static,66,array,public
From: https://www.cnblogs.com/xinay/p/16848859.html

相关文章