-
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);
}
}
}
}
-
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-
-
hmmm ... interesting ...
Can you kindly clarify or provide example of "loop just once"
-
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-
-
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-
-
Gary you ROCK!
Thanks man!