I am learning recursion and I am supposed to create a recursive method to count number of apperances of a specific number in an array, e.g.; {1,2,3,4,4,5} for number 4 should return 2. I know that recursion is not the ideal problem to solve this issue and I know that using endIndex is not ideal either, but that's just a textbook problem I can't seem to solve.
My method is not working well, since I always run out of heap when running through big arrays. How would I optimize such code? Thanks!
public static int countNumber(int[] array, int startIndex, int endIndex, int
number) {
int result = 0;
if (startIndex==endIndex) {
return result;
}
if (array[startIndex] == number ) {
result++;
}
result = result + countNumber(array,startIndex+1,endIndex,number);
return result;
}