Question:
public static <T extends Comparable<T>> int findMinRecursive(T[] arr): Should behave just like findMin, but should be implemented recursively. Your method may not contain any while or for loops. Hint: the public findMinRecursive method should not, itself, be recursive. Instead, write an additional private helper method with additional parameters. This private helper method should be called from findMinRecursive. This must run in O(n) time.
Here is findMin:
public static <T extends Comparable<T>> int
findMin(T[] arr) {
int index = 0;
T min = arr[index];
for (int i = 1; i < arr.length; i++) {
if (arr[i].compareTo(min) < 0)
{
min =
arr[i];
index = i;
}
if (arr[i].compareTo(min) == 0)
{
min = min;
}
}
return index;
}
This is the code I have right now (main method for testing) - and it just returns zero:
public static <T extends Comparable<T>> int
findminRecursive(T[] arr) {
int index = 0;
int i = 1;
T min = arr[0];
int minvalue = helper(index, i, min, arr);
return minvalue;
}
public static <T extends Comparable<T>>
int helper(int index, int i, T min, T[] arr) {
if (i < arr.length &&
arr[i].compareTo(min) < 0) {
min =
arr[i];
index = i;
i++;
helper(index, i,
min, arr);
}
else if (i < arr.length
&& arr[i].compareTo(min) == 0) {
min = min;
i++;
helper(index, i,
min, arr);
}
else if (i < arr.length
&& arr[i].compareTo(min) > 0) {
min = min;
i++;
helper(index, i,
min, arr);
}
return index;
}
public static void main(String[] args) {
Integer[] test = {7,90,10,2,15,23,3,217,3,1};
System.out.println(findminRecursive(test));
}
Ïm stuck... Thanks!
public class FindMinRecursive { public static <T extends Comparable<T>> T findminRecursive(T[] arr) { return helper(arr, arr.length); } public static <T extends Comparable<T>> T helper(T[] arr, int size) { if (size == 1) { return arr[0]; } else { T min = helper(arr, size - 1); if (arr[size - 1].compareTo(min) < 0) { min = arr[size - 1]; } return min; } } public static void main(String[] args) { Integer[] test = {7, 90, 10, 2, 15, 23, 3, 217, 3, 1}; System.out.println(findminRecursive(test)); } }
Get Answers For Free
Most questions answered within 1 hours.