Reputation: 13
Currently I am trying to find the minimum value within the array. The user types in the array they want to create and then the program is supposed to find the minimum. I have tried using the max_int value to find he minimum but I haven't had any success. How can I find the minimum within the array?
public class Recursion {
public static int findMin(int[] array, int index, int min) {
int smallest = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
return findMin(array, index, min);
}
return smallest;
}
}
Upvotes: 1
Views: 146
Reputation: 1423
From your description, you just need to find the min value in the array, so you don't need to use recursion for this problem. The following is an adaptation from your original code that does the job.
public static int findMin(int[] array) {
int smallest = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
return smallest;
}
If you can use the Stream
interface, you can use a one liner for this problem.
public static int findMin(int[] array) {
return Arrays.stream(array).min().getAsInt();
}
Upvotes: 4
Reputation: 18245
Why do not just find min?
public static int findMin(int[] arr) {
int min = Integer.MAX_VALUE;
for (int a : arr)
min = Math.min(min, a);
return min;
}
or even:
public static int findMin(int[] arr) {
return Arrays.stream(arr).min().getAsInt();
}
Upvotes: 3