Java Function to Calculate Statistical Mode

Tuesday January 10, 2006

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;	    
	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;
	return mode;

Hope this helps someone!

comments 2 Comments | days old 6738 days old | Direct Link

Take another look...
Wednesday March 21, 2007

Hate to say it, but this method is deeply flawed. Consider these scenarios:

1. What if given the set [1,1,3,5,5]? What is the "actual" mode, and what does your method return?

2. What if given the set [1,2,3000000]? What happens to your valCounts array when you say "valCounts[val]++"? This may not break the method, but it's almost certainly not when you intended...because you're later going to loop over a very large array.

Back to the drawing board...

Good Call
Monday April 2, 2007

Thanks for your observation! I will definitely have to give this a little more thought.

post comment Post a Comment

Nobody is going to buy your viagra and gucci bags just because you post 1000 links on an obscure blog!
Contact me if you want to post a comment