954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

to secomd smallest number in array

i want to find the second smallest number ib array but it is displaying second highest number
int max=0,second=0;
if(a[0]>a[1])
{
max=a[0];
second=a[1];
}
else
{
max=a[1];
second=a[0];
}
for( i=2;i=max)
{
second=max;
max=a[i];
}
else

if(a[i]>second)
second=a[i];

}
System.out.println("the second smallest nubmer is"+second);

pavani2006
Newbie Poster
20 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

I would suggest to sort the array first and then it is simple just reguest number on second possition. Also keep in mind that you may have first two number of same value so the second smallest should be on 3rd position(but that is just extra feature of your program)

peter_budo
Code tags enforcer
Moderator
15,436 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 902
 

Your instructor could also be extra devious and give you an array where all the indecies hold the same value. In which case the second smallest number would still be that value

MacGyver Orca
Light Poster
39 posts since Jan 2007
Reputation Points: 19
Solved Threads: 4
 

no i gave all diff values

pavani2006
Newbie Poster
20 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 
ajay_tabbu
Junior Poster in Training
52 posts since Feb 2007
Reputation Points: 24
Solved Threads: 0
 

Already I can see problem here, in both cases if/else statement will be useless if first two numbers will be some of largest. You are expecting smallest number to be on one of first two positions in array.
Consider following array and think about it again
arr = {4, 5, 1, 3, 2}

peter_budo
Code tags enforcer
Moderator
15,436 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 902
 
Already I can see problem here, in both cases if/else statement will be useless if first two numbers will be some of largest. You are expecting smallest number to be on one of first two positions in array. Consider following array and think about it again arr = {4, 5, 1, 3, 2}



yaa sir u r right on run this code ans is 3 which is wrong.now i will try to slove this wiht my code.
thanking u

ajay_tabbu
Junior Poster in Training
52 posts since Feb 2007
Reputation Points: 24
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You