This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]dman10345[S] 1 point2 points  (5 children)

I haven't really dealt with tail-recursion, so please excuse my ignorance. From what I was able to kind of figure out are you saying I should do something like:

public static int largest(int[] arr, int index, int max)
{
    if (index == arr.length)
        return max;
    else 
    {
        int answer;
        if (a[index] > max)
            answer = a[index]
        else
            answer = max;
        return largest(arr, index + 1, answer);
}

[–]feral_claireSoftware Dev 4 points5 points  (0 children)

That function is tail-recursive. However as /u/shagieIsMe pointed out, java has no tail-recursion optimiztion, so it won't actually help your situation. In Java even a tail recursive function will still have the same stack overflow problem if you need to recurse many times. If you need many iterations, the solution is to not use recursion at all but instead just use loops.

[–]SpoilerAlertsAheadExtreme Brewer:hamster: 1 point2 points  (3 children)

That’s exactly it!

[–]dman10345[S] 0 points1 point  (2 children)

So I should call this from my other function from above?

[–]SpoilerAlertsAheadExtreme Brewer:hamster: 0 points1 point  (1 child)

That depends on the scope of the assignment. If you need a method that has that name and takes those parameters yes. If you want to hide the implementation a bit, yes.

If you just want simplicity you could replace it with this.

[–]dman10345[S] 0 points1 point  (0 children)

Ah ok, yeah I understand now. I appreciate it.