Find out the second highest in array I want to find the first and second highest number in an array. I could come up with one solution, but I want to know the optimum solution to do the same. Can someone help me with some alternative solution to this?

int main() 
{

    int arr[10] = {0,1,2,13,4,5,9,8,11,6};
    int first = arr[0];
    int second = arr[0];
    int i;

    for(i=0;i&lt;10;i++)
    {
        if(first &lt; arr[i])
        {
            second = first;
            first = arr[i];
        }
        else if(second &lt; arr[i])
        {
            second = arr[i];
        }

    }

    printf("First = %d\n", first);
    printf("Second = %d\n", second);


    return 0;
}


Output:




First = 13
Second = 11
There is a problem in your code. Assuming that input is [3, 2, 1], the program will work like this.


Set first and second as 3.
Iterate through elements noticing that nothing is larger than 3.
Claim that 3 is the second number.


To fix this, you can do something like this.

if (arr[0] &lt; arr[1]) {
    second = arr[0];
    first = arr[1];
}
else {
    second = arr[1];
    first = arr[0];
}

for (i = 2; i &lt; elems; i++) {
    /* Your code */
}


Also, your program doesn't work well when NaN is involved in first position. This probably doesn't really matter (currently this handles integers, not double floating point numbers), but this may be still relevant for you, as it would require some special code to handle NaN.