Java找出一組數位最大值

來源:互聯網
上載者:User

標籤:turn   eve   排序   onclick   abd   amp   bsp   max   find   

形如:int [] nums = {7,2,8,9,1,12};

解一:兩兩比較並記錄下標,下次比較拿上次比較的最大值和上次比較的下一個進行比較,迴圈一次找出最大值

 1 /** 2      * @author 馬向峰 比較一遍找出最大值 3      * @param arr 4      * @return 5      */ 6     private static int getMaxNum(int[] arr) { 7  8         // 記錄下標 9         int index = 0;10         // 假設第一個為最大值11         int max = arr[0];12         for (int i = index; i < arr.length; i++) {13             if (i + 1 < arr.length && max < arr[i + 1]) {14                 index = i + 1;15                 max = arr[i + 1];16             }17         }18         return max;19     }
View Code

解二:冒泡排序法

 1 private static int findMaxNum(int[] arr) { 2  3         for (int i = 0; i < arr.length; i++) { 4             for (int j = 0; j < arr.length - i - 1; j++) { 5                 if (arr[j] < arr[j + 1]) { 6                     int temp = arr[j]; 7                     arr[j] = arr[j + 1]; 8                     arr[j + 1] = temp; 9                 }10             }11         }12 13         return arr[0];14     }
View Code

 

Java找出一組數位最大值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.