I'm trying to find the minimum value of numbers in an array but it doesn't always work out properly. This is the code I wrote:
for (int i=0; i < arr.length; i++ ) {
min = arr[i];
for (j=0; j < arr.length; j++) {
if (arr[j] < arr[0]) {
min = arr[j];
}
}
}
Can someone correct me please?
If
arr
is an array of non-primitive numerics, I'd recommendjava.util.Collections.min(java.util.Arrays.asList(arr));
as that will be simpler to maintain. There's some justification in reverting to hand-coding if you need to pull the minimum and maximum out at the same time but I'd advise against hand-coding loops if there's a library function available.
In any case, you ought to check
arr != null
and the existence of a zeroth element.min now contains minimum value.
One option is sort your array and get the first element:
There's no need for the outer loop, it only runs once and you don't use
i
anyway. why do you have it?For the inner loop, you need to compare against the minimum value. Right now you are comparing it against the first element in the array, which is not necessarily the minimum value.
Also you could start the loop at 1, since you don't need to compare
arr[0]
against itself (it was just assigned tomin
)TRY this:
A way to do it would be using the java.util.Arrays class:
Example:
From the Java doc, Arrays.sort(int[]) sort the specified array into ascending numerical order.
So the output here prints 1.