代码:
1 public class Test { 2 public static int[] bublle_sort(int a[]){ 3 for (int i = 0; i < a.length-1; i++) { 4 boolean exchange = false; 5 for (int j = 0; j < a.length-i-1; j++) { 6 if (a[j+1]<a[j]){ 7 int tmp = a[j]; 8 a[j] = a[j+1]; 9 a[j+1]=tmp; 10 exchange = true; 11 } 12 13 } 14 if (exchange = false){ 15 break; 16 } 17 } 18 return a; 19 } 20 21 public static void main(String[] args) { 22 //冒泡排序 23 System.out.println("************before bublle_sort**************"); 24 int a[] = new int[5]; 25 for (int i = 0; i < a.length; i++) { 26 a[i] = (int)(Math.random()*100); 27 System.out.println("原始数据:"+a[i]); 28 } 29 System.out.println("************after bublle_sort**************"); 30 bublle_sort(a); 31 for (int i = 0; i < a.length; i++) { 32 System.out.println(a[i]); 33 } 34 35 }
冒泡排序的时间复杂度位O(n^2),但是理想情况下为O(n),记忆口诀:外管轮流内管排