# 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>1);
max=array[0]>array[1] ? array[0] : array[1];
secondmax=array[0]>array[1] ? array[1] : array[0];
for(j=2;j<n;j++)
{
if(array[j]> max) { secondmax=max;max=array[j];}
else if (array[j] > secondmax) { secondmax=array[j];}
}
return secondmax;
}

• Is code correct?

• Is usage of assert okay or should it be avoided?

• The working code is at ideone.com/ko0ID
– xyz
Commented May 29, 2011 at 14:00

There's no need to check if array[0] > array[1] twice.

if (array[0] > 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<n;j++)
{
int candidate = array[j];
if (candidate > max) {
secondmax = max;
max = candidate;
}
else if (candidate > 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.

• One quick question: am i missing sth here? how to uniformly indent in stackoverflow editor ? tab doesnt work.. anything inbuilt so that we dont have to count 5 spaces for each line. please let me know, because I often post code and everytime people complain of indenting and formating -- Thanks.
– xyz
Commented May 30, 2011 at 13:00
• I guess after years of doing it by hand I just got used to it. There's a toolbar button above the editor that will indent everything four spaces to make it code, and you could use that on each block successively to get to the right spacing I suppose. When I need to write a larger example I will do so in an editor that does the tab-to-space thing for me and then paste it here. Commented May 30, 2011 at 21:09