Java 程式計算 Java 中的眾數


在統計數學中,眾數是指出現次數最多的一個值。例如,假設一組值 3、5、2、7、3。這個值集的眾數是 3,因為它比任何其他數字出現的次數都多。

演算法

1.Take an integer set A of n values.
2.Count the occurrence of each integer value in A.
3.Display the value with the highest occurrence.

示例

演示

public class Mode {
   static int mode(int a[],int n) {
      int maxValue = 0, maxCount = 0, i, j;

      for (i = 0; i < n; ++i) {
         int count = 0;
         for (j = 0; j < n; ++j) {
            if (a[j] == a[i])
            ++count;
         }

         if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
         }
      }
      return maxValue;
   }
   public static void main(String args[]){
      int n = 5;
      int a[] = {0,6,7,2,7};
      System.out.println("Mode ::"+mode(a,n));
   }
}

輸出

Mode ::7

更新於: 2020-3-13

1.4 萬+ 瀏覽次數

啟動你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.