Its purpose is to be 0, so it could be
checked against the number of elements
in an array to return either -1 or
highest number;
Zero doesn't need a name - if you mean 0, use the literal 0
.
Your loop is fine. There are things you could do to try to optimise it, but they won't necessarily help. Almost always you may as well just leave such localised, "keyhole" optimisation to the JIT. If you just want to try a few things as a learning exercise, then you could experiment as follows:
- rather than using the array twice, set a variable to the array value, then use it twice.
- unroll the loop by different amounts. Be careful not to make the error of accessing the wrong indices if
numElem
isn't a multiple of the number of times you're unrolling.
- work backwards through the array instead of forwards
- return immediately if you encounter a value of
Integer.MAX_VALUE
. You aren't going to find anything bigger. It's difficult to define the performance effect of this, since it will speed it up for large arrays with a MAX_VALUE that isn't too near the end, but most likely slow it down for everything else. It might be interesting to see how much difference it makes, though.
- anything else you can think of.
I'm not saying any of these will make a difference, faster or slower, but they could. So run them and time how fast each goes. What you'll most likely learn, is that compared with leaving it to the JIT this stuff isn't worth your time. But you never know ;-)
The surrounding code can be cleaned up, though, to make it more comprehensible rather than to make it faster. For example:
public int getMax() {
int max = -1;
if (nElems > 0) {
max = array[0];
for(int j=1; j<nElems; j++) {
if(max < array[j])
max = array[j];
}
}
return max;
}
This also removes the error in your code, that if the array is size 0, then you access out of bounds in the second line. ColinD's way of doing that is just as good, I'm showing something different for the sake of variety.
Here's the shorter code assuming all values are non-negative:
public int getMax() {
int max = -1;
for(int j=0; j<nElems; j++) {
if(max < array[j])
max = array[j];
}
return max;
}