java 數組的冒泡排序

  

冒泡排序
(1)冒泡排序算法的運做以下:(從後往前)
  1. 比較相鄰的元素。若是第一個比第二個大,就交換他們兩個。
  2. 對每一對相鄰元素做一樣的工做,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。
  3. 針對全部的元素重複以上的步驟,除了最後一個。
  4. 持續每次對愈來愈少的元素重複上面的步驟,直到沒有任何一對數字須要比較。
(2)代碼展現(java)
  int scoreArray2 []=new int [] {10,32,43,57,85,95,43,78,90,56};
  int count=0;//定義交換的次數
  int count2=0;//定義比較的次數
  for (int i = 0; i < scoreArray2.length; i++){
    for (int j = i+1; j < scoreArray2.length; j++){
      if(scoreArray2[i]>scoreArray2[j]){
        int temp=scoreArray2[j];
        scoreArray2[j]=scoreArray2[i];
        scoreArray2[i]=temp;
        count++;
      }
      count2++;
    }
  }
   //for-each遍歷排序後的數組
  for (int i : scoreArray2){
    System.out.println(i);
  }
  System.out.println("共交換了"+count+"次");
  System.out.println("共比較了"+count2+"次");
 
  冒泡排序的核心代碼就是交換
   int temp=scoreArray2[j];
   scoreArray2[j]=scoreArray2[i];
   scoreArray2[i]=temp;
  比較次數固定,速度慢,當數據量大時就不適用了
相關文章
相關標籤/搜索