C++ Finding the mode of a sorted array

Hi!
I have a function that needs to calculate the mode of a sorted array. The mode however, does not return the correct function. Anyone know how to fix my code? The array is a list of numbers, btw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void calculateMode(int array[], int size)
{
    
        int counter = 0;
        int max = 0;
        //int mode = 0;
        for (int pass = 0; pass < size - 1; pass++)
            for (int count =  0; count < size; count++)
            {
                if (array[count] = array[count]+1)
                {
                    max = array[count];
                    counter = array[pass];
                }
            
            }
    
    cout << "The mode is: " << counter << endl;
}
If the array is already sorted, then you do not need nested loops. You can do this with a single loop in O(n) time.

Try the following code. (May need some debugging)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void calculateMode(int array[], int size)
{
    
        int counter = 1;
        int max = 0;
        int mode = array[0];
        for (int pass = 0; pass < size - 1; pass++)
        {
           if ( array[pass] == array[pass+1] )
           {
              counter++;
              if ( counter > max )
              {
                  max = counter;
                  mode = array[pass];
              }
           } else
              counter = 1; // reset counter.
        }
    cout << "The mode is: " << mode << endl;
}
Topic archived. No new replies allowed.