I don't quite understand recursion yet and I have some homework that I can't solve. Does anyone have an idea?
Task 1: Implement an int-method max(int[]arr, int i) which returns the maximum of all elements of arr with an index <= i.
This is my code thus far:
private static int max = 0;
private static int max(int[] arr, int i) {
if (i >= 0 && i < arr.length) {
if (arr[i] >= max) {
max = arr[i];
}
max(arr, i - 1);
}
return max;
}
Actually it works, but it's bad style, so my question is: How can I implement the recursive method without the private static int max? I am not allowed to add a third parameter to the method.
Task 2: Implement a boolean-method containsValue(int[] arr, int val) which returns true if one of the elements of arr matches val. The method should have two recursive calls: one which searches the first half of the array and one that searches the second half. You can use Arrays.copyOfRange(...).
This is my code:
private static boolean containsValue(int[] arr, int val) {
if (arr.length > 1) {
if (arr[arr.length - 1] == val) {
return true;
}
return containsValue(Arrays.copyOfRange(arr, 0, arr.length-1), val);
}
return false;
}
This also works and I understand why, but obviously the method doesn't have two recursive calls. Every attempt to implement the method dividing the array in two halves was a huge failure. Can anyone help me?