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.

3
  • 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. Commented Dec 4, 2013 at 18:55
  • How long is the array? Commented Dec 4, 2013 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 Commented Dec 4, 2013 at 23:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.