user5661402 user5661402 - 3 months ago 6
C Question

How to find the 2nd largest number in the array, but return the last index that the value appears in?

My actual problem is to find the number in a data set with the 2nd highest frequency. I'm initializing an array that is the size of the largest number in the data set and then incrementing the corresponding indexes in the array each time the number appears in the data set. If more than two indexes shares the 2nd highest frequency then I need to return the larger index. My code returns the correct answer in some cases, but not all and I am having trouble finding the error in my logic.

int secondFreq(int data[], int maxNum){
int highest = 0;
int secondHighest = 0;
int x;

for(x = 0; x < maxNum; x++){
if(data[x] > data[highest]){
secondHighest = highest;
highest = x;
}
else if (data[x] > data[secondHighest]){
secondHighest = x;
}
else if (data[x] == data[secondHighest]){
secondHighest = x;
}
}

return secondHighest + 1;
}


Here is an example of an array that yields the wrong answer. The left number is the index and the right number is the value stored at that index. My function returns 12 (11th index+1), but it should be returning 5 (4th index + 1).

0 - 2
1 - 2
2 - 5
3 - 2
4 - 5
5 - 4
6 - 2
7 - 2
8 - 6
9 - 4
10 - 3
11 - 6
12 - 2
13 - 2
14 - 3

Answer

your code has two problem.

  1. You will need to highest = x; in the case of data[x] == data[highest].
  2. secondHighest should is initially pending.

The following is an example of modification.

int secondFreq(int data[], int maxNum){
    int highest = 0;
    int secondHighest, secondFlag = 0;//secondFlag : Whether secondHighest has been determined, 0 : undetermined, 1(Not 0) : determined
    int x;

    for(x = 1; x < maxNum; x++){
        if(data[x] > data[highest]){
            secondHighest = highest;
            highest = x;
            secondFlag = 1;
        }
        else if (data[x] == data[highest]){
            highest = x;
        }
        else if (secondFlag == 0 || data[x] >= data[secondHighest]){
            secondHighest = x;
            secondFlag = 1;
        }
    }

    if(secondFlag)
        return secondHighest + 1;
    else
        return 0;//All elements same
}
Comments