# need a better way

• 05-06-2010, 02:08 AM
mac
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

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);
}
}
}
}

• 05-06-2010, 02:17 AM
gcalvin
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-
• 05-06-2010, 02:23 AM
mac
hmmm ... interesting ...

Can you kindly clarify or provide example of "loop just once"
• 05-06-2010, 02:29 AM
gcalvin
Sorry, you're already looping just once. But you only need two comparisons each time through the loop.

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-
• 05-06-2010, 02:34 AM
gcalvin
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-
• 05-06-2010, 02:35 AM
mac
Gary you ROCK!
Thanks man!