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 !
 
 
7 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
 
 
I am writing a research paper and collecting information on this topic. Your post is one of the better that I have read. Thank you for putting this information into one location.
payday loan

03/07/2012
 
 
I have been seeking information on this topic for the past few hours and found your post to be well written and has solid information.
Love Sms

03/07/2012
 
 

I have found your blog long ago and continue reading it up-to-date! But now I have decided to register and write a comment for those who are here for the first time! Do not pass by!! Do not look at the site design! The content is surely what you need from this topic! Stay with us and enjoy!
www.kinderspielzeugonlineversand.com

05/04/2012
 
 
Alright i execute the code and there wereno errors and you are right on what you say "further implementations on the loop, there is no value originate which is superior than a[n-2]." I was going to write if(a[i] != a[n-2]) secmax = a[i]; as there may be same numbers. I am currently enrolled into my Master's program in computer science at Headway University and regarding this topic hopefully my input will help you for sure.

05/08/2012
 
 
 
 
Add an answer*
 
Your name
Email
 
Location: Israel
logic developer algorithem

add a question

arrow_blue


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