冒泡

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

 

相关文章:

  • 2022-12-23
  • 2021-07-14
  • 2022-02-06
  • 2021-12-27
  • 2021-03-31
  • 2021-05-01
猜你喜欢
  • 2021-11-05
  • 2022-02-23
  • 2021-10-26
  • 2021-11-18
相关资源
相似解决方案