冒泡排序(Bubble Sort)是一種簡單的排序算法。它重復地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重復地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個算法的名字由來是因為越小的元素會經由交換慢慢“浮”到數列的頂端。
冒泡排序算法的運作如下:
- 比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
- 對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。在這一點,最后的元素應該會是最大的數。
- 針對所有的元素重復以上的步驟,除了最后一個。
- 持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
冒泡排序的過程圖:
代碼:
1 public class BubbleSort{
2 public static void main(String[] args){
3 int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
4 for (int i = 0; i < score.length -1; i++){ //最多做n-1趟排序
5 for(int j = 0 ;j < score.length - i - 1; j++){ //對當前無序區間score[0......length-i-1]進行排序(j的范圍很關鍵,這個范圍是在逐步縮小的)
6 if(score[j] < score[j + 1]){ //把小的值交換到后面
7 int temp = score[j];
8 score[j] = score[j + 1];
9 score[j + 1] = temp;
10 }
11 }
12 System.out.print("第" + (i + 1) + "次排序結果:");
13 for(int a = 0; a < score.length; a++){
14 System.out.print(score[a] + "\t");
15 }
16 System.out.println("");
17 }
18 System.out.print("最終排序結果:");
19 for(int a = 0; a < score.length; a++){
20 System.out.print(score[a] + "\t");
21 }
22 }
23 }
參考資料:http://zh.wikipedia.org/wiki/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F