Second largest element of a large array Given an array which contains integers (may contain thousands of elements), you have to write a program to find the second largest element of the group.

int secondmax(int array[],int n)
{
 int max;
 int secondmax;
 assert(n&gt;1);
 max=array[0]&gt;array[1] ? array[0] : array[1];
 secondmax=array[0]&gt;array[1] ? array[1] : array[0];
 for(j=2;j&lt;n;j++)
 {
  if(array[j]&gt; max) { secondmax=max;max=array[j];}
  else if (array[j] &gt; secondmax) { secondmax=array[j];}
 }
 return secondmax;
}



Is code correct?
Is usage of assert okay or should it be avoided?
There's no need to check if array[0] > array[1] twice.

if (array[0] &gt; array[1]) {
    max = array[0];
    secondmax = array[1];
} else {
    secondmax = array[0];
    max = array[1];
}


But if you really want to use the ternary operator here (? :), at least move them to the declarations, and move the assertion above.

It's a micro-optimization, but I would assign array[j] to a temporary variable inside the loop since it may potentially be accessed four times. Plus it is more readable

for(j=2;j&lt;n;j++)
{
    int candidate = array[j];
    if (candidate &gt; max) {
        secondmax = max;
        max = candidate;
    }
    else if (candidate &gt; secondmax) {
        secondmax = candidate;
    }
}


Gotta say that I'm not a big fan of a single space for indentation or putting multiple statements on a single line. I've worked at a company where we used two before, and that was confusing. One is asking for trouble. And with 24+ inch monitors common, there's no need to be so frugal with your vertical screen real estate! :)

The assertion seems like a good choice, though you might consider returning a signaling value instead. It really depends on what callers will expect, and make sure you document your choice.