Skip to content

Instantly share code, notes, and snippets.

@futureperfect
Created October 14, 2013 20:11
Show Gist options
  • Save futureperfect/6981458 to your computer and use it in GitHub Desktop.
Save futureperfect/6981458 to your computer and use it in GitHub Desktop.
Find the mode of a sorted array of integers
//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