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
廣告