冒泡排序

public class Demo {
    public static void main(String[] args) {

        int[] arr = { 24, 69, 80, 57, 13 };
        System.out.println("排序前:");
        printArray(arr);

        bubbleSort(arr);
        System.out.println("排序后:");
        printArray(arr);

       /*
        排序前:
        [24, 69, 80, 57, 13]
        排序后:
        [13, 24, 57, 69, 80]
        */
    }

    // 遍历功能
    public static void printArray(int[] arr) {
        System.out.print("[");
        for (int x = 0; x < arr.length; x++) {
            if (x == arr.length - 1) {
                System.out.print(arr[x]);
            } else {
                System.out.print(arr[x] + ", ");
            }
        }
        System.out.println("]");
    }

    //冒泡排序代码
    public static void bubbleSort(int[] arr){
        for (int x = 0; x < arr.length - 1; x++) {
            for (int y = 0; y < arr.length - 1 - x; y++) {
                if (arr[y] > arr[y + 1]) {
                    int temp = arr[y];
                    arr[y] = arr[y + 1];
                    arr[y + 1] = temp;

                }
            }
        }
    }

    //数组排序之选择排序
    //我们在上面的Demo中,只需用把上面冒泡排序的方法换成下面我们选择排序的方法
    public static void selectSort(int[] arr){
        for(int x=0; x

你可能感兴趣的:(冒泡排序)