Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Pre: The array passed in should already be sorted.
- //Post: Returns the number that occurs the most.
- //Purpose: Determine which number occurs most often in a sorted array.
- int CalcMode(/*IN*/ const IntArr& numArr, //Sorted array to calculate the mode for.
- /*IN*/ int numFilled) //Number of filled indices.
- {
- int modeInd = 0; //Index of the Mode
- int modeRun = 0; //Run Length of the current Mode
- int currInd = 0; //Index of Current Test
- int currRun = 0; //Current Run Length
- int ind = 0; //Working Index
- //Count the run for the first number in the array and initialize the currInd
- //I had this as an if inside the next while but it only executes for the first
- //number so I just separated it so it wasn't a Kobayashi Maru, hence wasting processing.
- while(numArr[ currInd ] == numArr[ modeInd ])
- {
- modeRun++;
- currInd++;
- }
- //Iterate through every element.
- while(ind < numFilled - 1)
- {
- //Test if the working num is part of the current run:
- if(numArr[ ind ] == numArr[ currInd ])
- {
- currRun++;
- }//end consecutivity test.
- else
- {
- currInd = ind;
- currRun = 0;
- }//end non-consecutive branch.
- //Test if the current run is longer than the recorded mode:
- if(currRun > modeRun)
- {
- modeInd = currInd;
- modeRun = currRun;
- //Move the currInd to the NEXT working index.
- currInd = ind + 1;
- currRun = 0;
- }//End if
- ind++;
- }//End while
- return modeInd;
- }//End CalcMode();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement