一、最简单的排序实现
冒泡排序是一种交换排序,其基本思想是:两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录为止。
1、 冒泡排序初级版
1 @Test 2 public void BubbleSort1(){ 3 int count =1; 4 int[] a={9,1,5,8,3,7,4,6,2}; 5 for(int i=0;i<a.length;i++){ 6 for(int j=i+1;j<a.length;j++){ 7 if(a[i]>a[j]){ 8 int temp=a[j]; 9 a[j]=a[i]; 10 a[i]=temp; 11 System.out.println("第 "+count +" 次"); 12 count++; 13 } 14 } 15 } 16 System.out.println(Arrays.toString(a)); 17 }
1、 正宗的冒泡排序
1 @Test 2 public void BubbleSort2(){ 3 int[] a={9,1,5,8,3,7,4,6,2}; 4 5 for(int i=0;i<a.length;i++){ 6 for(int j=a.length-2;j>=i;j--){ 7 if(a[j]>a[j+1]){ 8 int temp=a[j+1]; 9 a[j+1]=a[j]; 10 a[j]=temp; 11 12 } 13 14 } 15 } 16 System.out.println(Arrays.toString(a)); 17 }
3、冒泡排序优化
1 @Test 2 public void BubbleSort3(){ 3 boolean flag=true; 4 int[] a={9,1,5,8,3,7,4,6,2}; 5 for(int i=0;i<a.length&&flag;i++){ 6 flag=false; 7 for(int j=a.length-2;j>=i;j--){ 8 if(a[j]>a[j+1]){ 9 int temp=a[j+1]; 10 a[j+1]=a[j]; 11 a[j]=temp; 12 flag=true; 13 } 14 15 } 16 } 17 System.out.println(Arrays.toString(a)); 18 }
两种排序对比
1)
2)
冒泡排序复杂度分析