Find second max value in N size array

Question posted on 08 2010
Rate question difficulty level 1 Votes
You need to find the second max number in an array , you can use only one iteration !
 
 
2 Answers
 
Two ways: Sort array in descending order and fetch the 2nd element. Or use the following.

int SecondMax(int Array[], int ALength)
{
int Fmax,Smax;
Fmax=Smax=Araay[0];
for (int i = 0; i < ALength; i++)
{
if (Array[i] > Smax){
if (Array[i] < Fmax){
Smax = Array[i];
}
else{
Smax = Fmax;
Fmax = Array[i];
}
}
}
return Smax;
}

08/13/2010
 
 
Sorry to destroy your celebration, but both solutions seem to be wrong.
1. Sorting an array is at least O(n*log(n)), and not O(n), as instructed, so sorting is out of the question.
2. if Array[0] contains the biggest number, your solution will not work.
My solution:
int SecondMax(int array[], int length)
{
int max1, max2, i;

if(length <= 1) return -1; /* error */
max1=array[0];
max2=array[1];
if(max1 {
max1=array[1];
max2=array[0];
}
for (i = 2; i < length; i++)
{
if (array[i] > max2)
{
if (array[i] < max1)
{
max2 = array[i];
}
else
{
max2 = max1;
max1 = array[i];
}
}
}
return max2;
}

08/14/2010
 
 
Add an answer*
 
Your name
Email
 
Location: Israel
logic developer algorithem

add a question

arrow_blue


Now hiring!
---------------------------
---------------------------
---------------------------
---------------------------
Mercer 
---------------------------
---------------------------
---------------------------