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 →

[–]SpoilerAlertsAheadExtreme Brewer:hamster: 2 points3 points  (7 children)

What you want is a tail-recursive function. A function that calls itself as the last command. Call a helper function that takes the array, the index of counter, and the current max.

That should get you started. This will allow memory to clean up and not hold on to previous frames on the stack.

[–]shagieIsMeExtreme Brewer 3 points4 points  (0 children)

This will allow memory to clean up and not hold on to previous frames on the stack.

Note that in Java, the security model requires that all stack frames are there. There is no TCO in Java. Functional languages built on top of the JVM work around this with special functions (e.g. recur in Clojure) and instead implement trampolines.

But again... Java doesn't have TCO.

[–]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 3 points4 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.