BubbleSort

来源:互联网 发布:windows player手机版 编辑:程序博客网 时间:2024/05/19 02:00

冒泡算法的核心是相邻的两个元素进行比较,如果左边的数比右边的数要大,则利用一个exch()方法交换两个元素,并且利用一个标识符swap=true,表示数组中的元素仍没有排好序。利用一个for循环进行遍历比较相邻的两个元素。直到数组中是一个有序数组–等价于swap = false。

class BubbleSort {    public static void main(String[] args)    {        int[] a = new int[]{3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};        boolean swap;        do        {            swap=false;//比较完一次后将swap置成false,只要数组中没有交换的元素则执行for循环后就会跳出循环。            for (int i = 0;i<a.length-1 ;i++ )            {                if (a[i]>a[i+1])                {                    exch(a,i,i+1);                    swap = true;                }            }        }        while (swap);//只要swap为true表示数组中的元素进行排序,执行循环体        printArr(a);    }    public static void exch(int[] a, int i,int j)    {        int temp = a[i];        a[i] = a[j];        a[j] = temp;    }    public static void printArr(int[] a)    {        for (int i = 0;i<a.length ;i++ )        {            if (i==0)            {                System.out.print("{"+a[i]+",");            }            else if (i<a.length-1)            {                System.out.print(a[i]+",");            }            else                System.out.println(a[i]+"}");        }    }}
原创粉丝点击