0

I have a problem that gives Stack Overflow Error on my code. I'm trying to find a number in one array, but I have to do it in a recursive function, and gives that error.

public static int linear(int[] array, int num, int indice) {
    if (indice < array.length-1) {
        if (array[indice] == num) {
            return indice;
        } else {
            ocurrencias++;
            linear(array, num, indice + 1);
        }
    }
    return -1;
}

If you can help me I would appreciate. My english is a little rusty, sorry.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
André
  • 23
  • 4
  • 2
    What's the size of your array? If you are running into stackoverflow just use a simple for loop. If you have to use recursion, you will want to sort the array and use a binary search algorithm. – C.B. Dec 04 '13 at 18:55
  • How long is the array? – Oliver Charlesworth Dec 04 '13 at 18:55
  • the size of the array is inserted before by the user. And i have to use linear search to find the number, but using recursive function – André Dec 04 '13 at 23:51

1 Answers1

1

You're missing a return before the recursive call to linear, don't you?

return linear(array, num, indice + 1);

However, I don't think Java does tail-recursion-optimization (What is tail recursion?), so you have to increase your stack-size appropriately for huge arrays ;)

Community
  • 1
  • 1
hotzen
  • 2,800
  • 1
  • 28
  • 42
  • I had the return statement before "linear" but error appear as well. The variable indice starts at 0 and should increment until it is lower than array.length-1. If the array have 100 positions indice should stop at 99. – André Dec 05 '13 at 00:00