[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
Solved

# java lists

Posted on 2004-09-29
Medium Priority
223 Views
how can I find the second highest value in a list of integers? and also the second lowest ?
0
Question by:rwallacej
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2
• 2

LVL 1

Assisted Solution

djspinnet earned 800 total points
ID: 12179369
to find the second highest,

declare two variables max and second_max

1) traverse the list
2) store the first integer in max
3) if the next int (let's call it x) is larger than max, assign second_max = max; and max = x;
4) continue traversing the whole list and performing the same operation
5) return second_low

same goes for second lowest, just change >= to <=
0

LVL 1

Accepted Solution

csaba_b earned 1200 total points
ID: 12180266
Hi djspinnet!
your solution won't work for the following list: 2, 1 ... sorry

my proposal is:

suppose the list contains at leas 2 members and in case when two members has the highest value, the second highest equals the highest :)

int max = ((Integer)list.next()).intValue();
int max2 = ((Integer)list.next()).intValue();
int mxc = max2;
while(true) {
if(mxc>=max) {
mx2 = max;
max = mxc;
} else if(mxc>max2) {
max2 = mxc;
}
if(!list.hasNextt()) {
break;
}
mxc = ((Integer)list.next()).intValue();
}

for the second lowest you just replace > with <

csaba
0

LVL 21

Expert Comment

ID: 12180827
If speed is not an issue, just sort the list and grab the 2nd and 2nd from last item from the list
Collections.sort(l);
small=l.get(1);
large=l.get(l.size()-2);
0

LVL 1

Expert Comment

ID: 12188464
actually, my solution did work - i implemented it once ;)
0

LVL 1

Expert Comment

ID: 12402861
To djspinnet:

Have you tried your algorithm with the list I mentioned? If yes, and the result was correct. you can accept the points offered.

I don't think so ...

Csaba
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Progress
###### Suggested Courses
Course of the Month14 days, 2 hours left to enroll