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 <
A way to do it would be using the java.util.Arrays class:
Example:
public class ArraySort {
public static void main(String[] args) {
int[] array = {12, 4, 6, 1, 56, 21, 77};
Arrays.sort(array);
System.out.println(array[0]);
}
}
From the Java doc, Arrays.sort(int[]) sort the specified array into ascending numerical order.
So the output here prints 1.
Here is a general algorithm for doing this. You can write the code for it.
Store the first item in the array as the current minimum.
Loop through the array, starting at the second item (index 1).
For each iteration of the array, check if the current item is less than the minimum. If it is, store it as the new minimum.
Once the loop ends, you have the minimum!
You are checking the first element in each iteration, you basically need to check minimum value
if (arr[j] < min) {
min = arr[j];
}
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.
min = arr[0];
for (j=0; j < arr.length; j++) {
if (arr[j] < min) { //<---fix is here
min = arr[j];
}
}
Also you could start the loop at 1, since you don't need to compare arr[0]
against itself (it was just assigned to min
)