Second Largest Array Sort

Given the following code which outputs the second biggest integer in an array of 4 integers why do you need the secondMax if statement before firstMax if statement?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    int firstMax = array[0];
    int secondMax = array[1];
    for (int i = 0; i < 4; i++)
    {
        if(array[i]>secondMax)
        {
            secondMax = array[i];
        }
        if (array[i]>firstMax)
        {
            secondMax = firstMax;
            firstMax=array[i];
        }

    }
    cout << secondMax;
    return 0;
}
That's in case array[i] is greater than secondMax but less than firstMax.
Hmmm. Let array = { 1, 2, 4, 3 }
fm=1, sm=2

i=0
1 !> 2
1 !> 1

i=1
2 !> 2
2 > 1, sm=1, fm=2

i=2
4 > 1, sm=4
4 > 2, sm=2, fm=4

i=3
3 > 2, sm=3
3 !> 4
Result: fm==4, sm==3
Topic archived. No new replies allowed.