在 Java 陣列中查詢第三小的數字。


示例

以下是必需的程式。

現場演示

public class Tester {
   public static int getThirdSmallest(int[] a) {
      int temp;
      //sort the array
      for (int i = 0; i < a.length; i++) {
         for (int j = i + 1; j < a.length; j++) {
            if (a[i] > a[j]) {
               temp = a[i];
               a[i] = a[j];
               a[j] = temp;
            }
         }
      }
      //return third smallest element
      return a[2];
   }
   public static void main(String args[]) {
      int a[] = { 11,10,4, 15, 16, 13, 2 };
      System.out.println("Third Smallest: " +getThirdSmallest(a));
   }
}

輸出

Third smallest: 10

更新於: 12-Mar-2020

4000+ 次瀏覽

開啟你的 職業生涯

完成學習以獲得認證

開始
廣告
© . All rights reserved.