Java基础 冒泡排序算法代码实例

版权声明:本文为博主原创文章,可以随意自由转载传播,但请注明出处. https://blog.csdn.net/aikongmeng/article/details/88546543
package maopao;

import java.util.Arrays;

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


        int[] arr = {6, 3, 8, 2, 9, 11, 21, 1, -2, -1};
        int[] arrs = new int[arr.length];
        System.arraycopy(arr, 0, arrs, 0, arr.length);
        System.out.println("排序前数组为:");
        printArr(arr);

        //
        Arrays.sort(arrs);
        System.out.println("Arrays排序:");
        printArr(arrs);


        for (int i = 0; i < arr.length - 1; i++) {//外层循环, 控制排序趟数
            int temp;
            for (int j = 0; j < arr.length - 1 - i; j++) {//内层循环,控制每一趟排序多少次
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println("排序后数组为:");
        printArr(arr);
    }

    private static void printArr(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();

    }
}

猜你喜欢

转载自blog.csdn.net/aikongmeng/article/details/88546543
今日推荐