1. 程式人生 > >java排序之冒泡排序

java排序之冒泡排序

sort stat false sys 復雜度 turn random mat 記憶

代碼:

 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),記憶口訣:外管輪流內管排

java排序之冒泡排序