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 Comments

Take another look...

by Reid

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

by Marty

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

Warning: scandir(/home/ilike/public_html/images/captcha): failed to open dir: No such file or directory in /home/ilikhjxv/public_html/index.php on line 243

Warning: scandir(): (errno 2): No such file or directory in /home/ilikhjxv/public_html/index.php on line 243

Warning: array_diff(): Argument #1 is not an array in /home/ilikhjxv/public_html/index.php on line 243
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