Tail recursive saves stack memory. A recursive function is said to be tailrecursive if there is nothing to do after the function returns except returning its value. In this case, instead of allocating a stack frame for each call, the compiler can rework the code to simply reuse the current stack frame, meaning a tailrecursive function will only use a single stack frame as opposed to hundreds or even thousands of stack frame as in the case of regular recursive calls. Also, in a tailrecursive case, with each evaluation of the recursive call, the solution (e.g., a running total) is updated through parameter. A smart compiler can make Tail Recursion as efficient as iteration normally is. We'll see an tailrecursion implementation of Fibonacci at the end of this post. Using Fibonacci as an example, a Fibonacci sequence: [f(0)...f(n)]=[0, 1, 1, 2, 3, 5, 8, 13, ...] A regular recursive implementation of Fibonacci: public double fib(int n) { The runtime breakdown of the above intuit but inefficient recursive algorithm which takes a lot of stack space: fib(100) You may notice the above algorithm will be terribly performed with O(2^n). For performance's sake, here's the nonrecursive version using a loop: double f(int n){ With the above nonrecursive code, to get fib(n), simply call f(n1). Can't we stay with the recursive way of implementation? Sure. I view tail recursion as a way of introducing a running total which is updated through parameter of the recursive calls. In the Fabonacci example below, 'running tatal' is updated and maintained through 'val' parameter, and the previous value to be calculated toward Fabonocci is passed through the 'prev' parameter: double fib(int term, double val = 1d, double prev = 0d) Consider the following tail recursion way of implementation using Groovy's default parameter (not supported by Java): double fib(int term, double val = 1d, double prev = 0d){ references
0 Comments
Leave a Reply. 
Categories
All
Archives
March 2018
