i was given the following problem: create a recursive method that checks if a given array contains a given value. This should be done by splitting the array in two halfes and therfore requires two recursive calls.
The problem for me is that the method head doesnt contain any specifieds index range, that can be altered with recursion, so that every value in the array is searched. I've now tried to just fix the index that is being compared to the value as 0 and continue to split up the array in halfes, so that every value in the array has the index 0 at some point. It doesn't work however and i don't understand why. If anyone could give me a clue as to what i'm doing wrong, that would be helpful, as I'm still very new to java.
My limitations are as follows: no altering of the method head, no global variables, no loops, only classes allowed are: String, Array, Math, Integer.
Example:
int[] array = {2, 4, 7, 10, -10, 4, 0, 0, 27, 11, 4, 6};
System.out.println(containsValue(array4, 11));
This should be true, in my code it is however false.
Code:
private static boolean containsValue(int[] workArray, int value) {
int count = 0;
boolean hasValue;
if (workArray.length > 1) {
int[] firstHalfArray = Arrays.copyOfRange(workArray, 0, (workArray.length / 2) - 1);
if (firstHalfArray[count] == value) {
hasValue = true;
return containsValue(firstHalfArray, value) || hasValue;
}
}
if (workArray.length > 1) {
int[] secondHalfArray = Arrays.copyOfRange(workArray, 6, workArray.length - 1);
if (secondHalfArray[count] == value) {
hasValue = true;
return containsValue(secondHalfArray, value) || hasValue;
}
}
return false;
}
public static void main(String[] args) {
int[] array4 = {2, 4, 7, 10, -10, 4, 0, 0, 27, 11, 4, 6};
System.out.println(containsValue(array4, 11));
System.out.println(containsValue(array4, 2));
System.out.println(containsValue(array4, 25));
System.out.println(containsValue(array4, 0));
System.out.println(containsValue(array4, 14));
System.out.println(containsValue(array4, 6));
}
Thanks in advance
Update: I have tuned and adjusted my code. My base case was horribly wrong, thanks for that. The rest of it still isnt working the way i want it to, even though for my the recursion is correctly implemented (I still continue to split it in half until the base case is reached (workArray.lenght == 1) and the check if that single int in the array is equal to value. What am I still doing wrong?
private static boolean containsValue(int[] workArray, int value) {
int count = 0;
if (workArray.length > 1) {
int[] firstHalfArray = Arrays.copyOfRange(workArray, 0, (workArray.length / 2));
return containsValue(firstHalfArray, value);
}
if (workArray.length > 1) {
int[] secondHalfArray = Arrays.copyOfRange(workArray, workArray/2, workArray.length - 1);
return containsValue(secondHalfArray, value);
}
if (workArray[count] == value) {
return true;
}
return false;
hasValuevariable shouldn't be there.