三、排序-冒泡排序

import java.util.Arrays;
/**
 * @author zhou 1
 * @date 2021-5-14
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] arr=new int[]{8,5,9,4,1,2,3,6,0};
        System.out.println(Arrays.toString(arr));
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    /**
     *  8,5,9,4,1,2,3,6,0   总共比较 length-1 轮
     *  5,8,9,4,1,2,3,6,0
     *  5,8,4,1,2,3,6,0,9   第一轮
     *
     * @param arr
     */
    public static void bubbleSort(int[] arr){
        // 控制比较多少轮
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

    }

}

运行结果:

[8, 5, 9, 4, 1, 2, 3, 6, 0]
[0, 1, 2, 3, 4, 5, 6, 8, 9]

原文地址:https://www.cnblogs.com/saysayzhou/p/14767854.html