【排序】冒泡排序

冒泡

package sort;

public class bubbleSort {
    public static void main(String[] args) {
        int[] a = new int[] {3, 5, 15, 6, 9, 7};
        bubblesort(a, 6);
        for(Integer i : a) {
            System.out.println(i);
        }
    }
    
    static void bubblesort(int[] a, int n) {
        for(int i = 0; i < n; i++) {
            boolean flag = false;
            for(int j = i+1; j < n - i; j++) {
                //后一个小于前一个 就交换
                if(a[j] < a[j - 1]) {
                    int temp = a[j];
                    a[j] = a[j -1];
                    a[j-1] = temp;
                    flag = true;
                }            
            }
            //flag 为false说明这一轮没有交换,后一个都大于前一个 ,即数组 已经有序了
            if(flag == false) break;
        }
    }
}
原文地址:https://www.cnblogs.com/chengdabelief/p/7479133.html