# Thread: need a better way

1. ## need a better way

hi guys,

the task is simple - from the list of numbers find the biggest and the smallest one.

This code works fine, but in my quest to seek perfection, i ask you if you can suggest a better implementation

Java Code:
```private static void sizeMatters(List<Double> numList) {
boolean runOnce = false;

for (int i = 0; i < numList.size(); i++) {
if (!runOnce) {
if (numList.get(i) < numList.get(i + 1)) {
smallNumber = numList.get(i);
bigNumber = numList.get(i + 1);
} else {
smallNumber = numList.get(i + 1);
bigNumber = numList.get(i);
}
runOnce = true;
} else {
if (smallNumber > numList.get(i)) {
smallNumber = numList.get(i);
}
if (bigNumber < numList.get(i)) {
bigNumber = numList.get(i);
}
}
}
}```

2. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
7
Declare a double smallest and double largest up front. Initialize them to Double.MAX_VALUE and Double.MIN_VALUE, respectively (that's right -- smallest gets set to MAX_VALUE and largest to MIN_VALUE). Loop just once, comparing each double to smallest and largest, and updating smallest and largest when appropriate. You don't need any runOnce or i + 1 stuff.

-Gary-

3. hmmm ... interesting ...

Can you kindly clarify or provide example of "loop just once"

4. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
7
Sorry, you're already looping just once. But you only need two comparisons each time through the loop.

Java Code:
```        double current = numList.get(i); // so we don't have to call .get() quite so much
if (current < smallest) smallest = current;
if (current > largest) largest = current;```
That's all.

-Gary-

5. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
7
Just to be clearer, it's basically what you have in your else {} block. You can easily avoid the runOnce stuff by properly initializing your smallNumber and bigNumber variables. (By the way, where are they declared? They must be instance variables in your class?) Either initialize them to MAX_VALUE and MIN_VALUE as I suggested, or just initialize them to numList.get(0) outside of the loop.

-Gary-

6. Gary you ROCK!
Thanks man!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•