c - How to find the 2nd largest number in the array, but return the last index that the value appears in? -
my actual problem find number in data set 2nd highest frequency. i'm initializing array size of largest number in data set , incrementing corresponding indexes in array each time number appears in data set. if more 2 indexes shares 2nd highest frequency need return larger index. code returns correct answer in cases, not , having trouble finding error in 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 example of array yields wrong answer. left number index , right number value stored @ index. function returns 12 (11th index+1), should 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
your code has 2 problems:
- you need set
highest = x;
in case ofdata[x] == data[highest]
. secondhighest
should pending.
the following example 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
Post a Comment