# Help with finding modal value

• 04-30-2008
packman
Help with finding modal value
I need to find an algorithm for finding the modal value of an array of numbers. I have the array organized in an ascending order. I suspected that the algorithm would be something like what you would use for a bubble sort, but I can't seem to make it work. Hopefully somebody can clue me in. Thanks.

The array is a total of 10 numbers.
• 04-30-2008
tabstop
The thing to note is that if your array is sorted, all the like numbers will have to be next to each other. So scan through the array looking for clumps of numbers -- the largest clump(s) is(are) the mode(s).
• 04-30-2008
packman
Yeah, I tried doing that by using a series of for loops with an if statement attached, but I can't seem to get it right.
• 04-30-2008
dwks
http://www.mathsisfun.com/mode.html

Perhaps the best way to find the mode would be to sort the numbers first (perhaps with a bubble sort like you mentioned), and then step through it to find the number that occurs the most. This latter step is pretty easy to do. You need a loop to iterate through the elements in the array, a maximum detected count, and perhaps a current count.

I suppose you could do this without sorting the array, but it would be rather difficult.

Personally, I might use a modified selection sort for this. It would let you sort the numbers and count how many occurrences of each number there are at the same time. The "sorted" array would just have to have a count associated with each number. For every element in the array, you would find the place in the sorted array that you would insert the new element. If the element already exists, you would increment the counter for that number instead of adding a new number to the list . . . .

Just some thoughts I had at first glance.