André
André

Reputation: 23

Recursive overflow

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.

Upvotes: 0

Views: 100

Answers (1)

hotzen
hotzen

Reputation: 2873

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 ;)

Upvotes: 1

Related Questions