Java------冒泡排序

冒泡排序算法的運作如下:

  1. 比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
    2.對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。在這一點,最后的元素應該會是最大的數。
  2. 針對所有的元素重復以上的步驟,除了最后一個。
    4.持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
public class BubbleSort{
       public static void main(String[] args){
           int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
           for (int i = 0; i < score.length -1; i++){    //最多做n-1趟排序
               for(int j = 0 ;j < score.length - i - 1; j++){    //對當前無序區間score[0......length-i-1]進行排序(j的范圍很關鍵,這個范圍是在逐步縮小的)
                   if(score[j] < score[j + 1]){    //把小的值交換到后面
                       int temp = score[j];
                       score[j] = score[j + 1];
                       score[j + 1] = temp;
                  }
              }            
              System.out.print("第" + (i + 1) + "次排序結果:");
              for(int a = 0; a < score.length; a++){
                  System.out.print(score[a] + "\t");
              }
              System.out.println("");
          }
              System.out.print("最終排序結果:");
              for(int a = 0; a < score.length; a++){
                  System.out.print(score[a] + "\t");
         }
      }
  }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容