# How to get the SECOND highest value in a for() loop?

Experts,
As this is the ‘programming’ forum, I hope this is appropriate. It is a purely language/function question. To put a finer point on the question, it has to be as simple/fast as possible (which I’ve already failed at below), as time in this loop is time not listening to the sensor, and I need to listen to it as much as possible to not ‘miss’ anything.

The code below is as good as I can get it for establishing a variable for the highest and 2nd highest value of a single variable in a for() loop:

``````// someArray[]... of ints...
int FirstHighestValue, SecondHighestValue;

for (uint16_t i = 0; i < sizeSomeArray; i++)
{
// find highest value
if (someArray[i] > FirstHighestValue) {
FirstHighestValue = someArray[i];
}
// find second highest
if ((someArray[i] > SecondHighestValue) && (someArray[i] < FirstHighestValue) && (FirstHighestFreq != someArray[i])) {
SecondHighestValue = someArray[i];
}
}
``````

My approach would be to 1) search for the highest value and remember it 2) zero out that array entry 3) search again 4) etc. for the third highest

``````for (uint16_t i = o;
``````

What is 'o' ?

GrooveFlotilla: ``` for (uint16_t i = o; ```

What is 'o' ?

Sorry, GV, that was supposed to be a zero(0)... fixed.

How are the values getting into the array in the first place ?

if you can’t sort indeed as the data is coming into the array, then your code is kinda OK

you need to initialize FirstHighestValue and SecondHighestValue to someArray[0] and start the for loop at index 1

but could be simplified

``````    if ((someArray[i ] > SecondHighestValue) && (someArray[i ] < FirstHighestValue) [color=red][s]&& (FirstHighestFreq != someArray[i ])[/s][/color]) {
``````

the last part is un-necessary since you know `someArray[i ] [color=red][b]<[/b][/color] FirstHighestValue`