數組選擇排序

中心思想:把一個數與沒有排序的數進行逐個比較,直到最後一個數爲止,然後把最值與首元素進行位置互換。

 

 

                     class  HomeWork2   {

                                 public static void main(String[] arg)

                       {

                               int[] scores = {6,19,7,28,1,9};  //  定義一個數組

                               for(int i = 0;i < scores.length; i++)  //    外循環,循環的是每個數

                                      {

                                           for(int j = i + 1; j < scores.length; j++)   //   第i個數與其他沒有排序的數進行比較 

                                                     {

                                                               if(scores[ j ] < scores [ i ])  //  條件判斷

                                                                      {

                                                                             int temp = scores[ i ];

                                                                             scores[ i ] = scores[ j ];

                                                                             scores[ j ] = temp;

                                                                     }

                                                      for(int value : scores)  //   遍歷數組

                                                             {

                                                                  System.out.println(value);

                                                             }

                        }

          }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章