JAVA中的经典算法之冒泡排序(BUBBLE SORT)

原理:比较两个相邻的元素,将值大的元素交换至右端(或者是将小值交换至右端)

逻辑思路参考:https://www.cnblogs.com/shen-hua/p/5422676.html

public class Bbble {

    public void BubbleSort(int[] arry) {
        for (int i = 0; i < arry.length; i++) {//外层循环控制排序趟数
            for (int j = 0; j < arry.length - i - 1; j++) {//内层循环控制每一趟排序多少次
                if (arry[j] > arry[j + 1]) {//'>'为升序排列,'<'为降序排列
                    int temp = arry[j];
                    arry[j] = arry[j + 1];
                    arry[j + 1] = temp;
                }
            }
        }
        //用集合的方式将数组打印出来
        List list=new ArrayList();
        for (int arr : arry) {
            list.add(arr);
            System.out.println("升序打印出的数组为"+arr);//此方式在于循环打印
        }
        System.out.println("集合升序打印出的数组为"+list);
    }




public class BubbleSort {

    public static void main(String[] args) {
        int[] arrys = {4, 7, 9, 10, 3, 5, 89, 0};
        Bbble bbble = new Bbble();
        bbble.BubbleSort(arrys);
    }

}


运行结果

升序打印出的数组为89
升序打印出的数组为10
升序打印出的数组为9
升序打印出的数组为7
升序打印出的数组为5
升序打印出的数组为4
升序打印出的数组为3
升序打印出的数组为0
集合方式升序打印出的数组为[89, 10, 9, 7, 5, 4, 3, 0]
原文地址:https://www.cnblogs.com/lindaiyu/p/10909566.html