Created
October 14, 2013 20:11
-
-
Save futureperfect/6981458 to your computer and use it in GitHub Desktop.
Find the mode of a sorted array of integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Find mode in sorted array | |
/* | |
What types? Let's assume int for now. | |
Bounds on underlying data? No bounds beyond underlying int type | |
Know anything about the distribution. Nope. Anything and everything, but the array is monotonically increasing. | |
What bounds on array size? Let's not concern ourselves. Sufficiently | |
small that we can work with the array in memory. | |
*/ | |
public class ArrayUtilities { | |
public static T findSortedArrayMode(int[] array) { | |
checkNotNull(array); | |
checkArgument(array.length > 0, "An array must contain items to have a mode"); | |
int potentialMode = Integer.MIN_INTEGER; | |
int potentialModeFrequency = Integer.MIN_INTEGER; | |
int currentItem = Integer.MIN_INTEGER; | |
long currentItemCount = 0; | |
for (int item : array) { | |
if (item == currentItem) { | |
++currentItemCount; | |
} else { | |
//replace biggest run stat with this if it is | |
if ((currentItemCount > 0) && (currentItemCount > potentialModeFrequency)) { | |
potentialMode = currentItem; | |
potentialModeFrequency = currentItemCount; | |
} | |
//reset currentItem to item and set count to 1 | |
currentItem = item; | |
currentItemCount = 1; | |
} | |
} | |
return potentialMode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment