Java------冒泡排序

冒泡排序算法的運(yùn)作如下:

  1. 比較相鄰的元素。如果第一個(gè)比第二個(gè)大,就交換他們兩個(gè)。
    2.對每一對相鄰元素作同樣的工作,從開始第一對到結(jié)尾的最后一對。在這一點(diǎn),最后的元素應(yīng)該會是最大的數(shù)。
  2. 針對所有的元素重復(fù)以上的步驟,除了最后一個(gè)。
    4.持續(xù)每次對越來越少的元素重復(fù)上面的步驟,直到?jīng)]有任何一對數(shù)字需要比較。
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++){    //對當(dāng)前無序區(qū)間score[0......length-i-1]進(jìn)行排序(j的范圍很關(guān)鍵,這個(gè)范圍是在逐步縮小的)
                   if(score[j] < score[j + 1]){    //把小的值交換到后面
                       int temp = score[j];
                       score[j] = score[j + 1];
                       score[j + 1] = temp;
                  }
              }            
              System.out.print("第" + (i + 1) + "次排序結(jié)果:");
              for(int a = 0; a < score.length; a++){
                  System.out.print(score[a] + "\t");
              }
              System.out.println("");
          }
              System.out.print("最終排序結(jié)果:");
              for(int a = 0; a < score.length; a++){
                  System.out.print(score[a] + "\t");
         }
      }
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容