美文网首页
冒泡排序

冒泡排序

作者: 从0到1的小姐姐 | 来源:发表于2019-04-14 15:56 被阅读0次
some some
思想 通过比较相邻两个元素之间的大小来进行排序,比较(n-1)轮(n是数组长度),第i轮比较n-i次。
时间复杂度 平均情况O(N2),最坏情况O(N2),最好情况O(N)
空间复杂度 O(1)
稳定性 稳定
public class BubbleSort2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a={8,35,48,62,15,5,2,3,65,4};
        BubbleSort2 bubble = new BubbleSort2();
        System.out.print("排序之前为:");
        bubble.show(a);
        System.out.println();
        bubble.sort(a);
        System.out.print("排序之后为:");
        bubble.show(a);
    }
    public void sort(int[] a){
        for(int i=1;i<a.length-1;i++){
            for(int j=0;j<a.length-i;j++){
                if(a[j]>a[j+1]){
                    int temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }
    }
    public void show(int[] a){
        for(int k:a){
            System.out.print(" "+k);
        }
    }
}

相关文章

网友评论

      本文标题:冒泡排序

      本文链接:https://www.haomeiwen.com/subject/alknhftx.html