Java Function to Calculate Statistical Mode
I looked everywhere on the web to find a java function to calculate the mode of an array of primitive ints. This will work for floats and long ints too, I suppose.
Anyway, since it was impossible to find, I figured I would post it here so maybe someone else can benefit.
public int calcMode(int[] sourceArray) {
int mode = 0;
Arrays.sort(sourceArray);
int[] valCounts = new int[(sourceArray.length-1)];
for(int val:sourceArray) valCounts[val]++;
int i = 0;
while(i < valCounts.length) {
if(valCounts[i] >= valCounts[mode]) mode = i;
i++;
}
return mode;
}
Hope this helps someone!
2 Comments
Direct Link