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 | 4487 days old | Direct Link

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...

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

Post a Comment

**COMMENTS CLOSED DUE TO SPAMMERS**

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