算法:冒泡算法及优化

算法:冒泡算法及优化

    代码如下:
public class MaoPao {
    public static int a[] ={1,2,3,4,5,6,7,8,9};
    public static void main(String args[])
    {
        sort();
        for (int k:
             a) {
            System.out.println(k);
        }
    }
    public static void sort()
    {
        for (int i =0;i <a.length;i++)
        {
            int flag = 0;
            for (int j = 0 ;j<a.length-i-1;j++)
            {
                if(a[j]>a[j+1])
                {
                    int temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                    flag = 1;
                }
            }
            if(flag == 0)
            {
                break;
            }
        }
    }
}

    核心思想:内层循环用于挨着的项前后比较,将最值传递到最后一位,外层循环用于不断缩小冒泡范围。

    优化方案:如果在某一次内层循环后,发现未出现交换处理,说明数组顺序,此时推出外层循环,实现方法可以在外层循环上设置一个flag,然后用作判断。

猜你喜欢

转载自blog.csdn.net/that_is_cool/article/details/80237081
今日推荐