80 likes | 181 Vues
Learn linear, tail, and higher-order recursion algorithms in C++ with examples like summing elements, reversing arrays by recursion, and computing powers. Explore iterative reversal and binary sum for efficient programming. See how recursion can be optimized through tail recursion in this educational guide.
E N D
Linear Recursion • Summing the Elements of an Array Recursively • Algorithm LinearSum(A, n): • Input: An integer array A and int n • Output: The sum of the first n int in A • if n = 1 then • return A[0] • else • return LinearSum(A, n-1) + A[n-1]
Linear Recursion • Reverse an Array by Recursion • Algorithm ReverseArray(A, i, n): • Input: An integer array A and int i, n • Output: The reversal of n integers in A starting at index i • if n > 1 then • Swap A[i] and A[i+n-1] • Call ReverseArray(A, i+1, n-2) • return
Linear Recursion • Computing Powers • Algorithm Power(x, n): • Input: The number x and int n >= 0 • Output: The value x power n • if n = 0 then • return 1 • if n is odd then • y Power(x, (n-1)/2) • return x * y * y • else • y Power(x, n/2) • return y * y
Tail recursion • Using recursion can often be a useful tool for designing algorithms, but this usefulness does come at a modest cost • Whenever we use recursion function to solve a problem, we have to use some of the memory locations in our computer to keep track of the state of each active recursive call • We can use the stack data structure to convert a recursive algorithm into a non-recursive algorithm, easily the ones which use tail recursion • A tail recursion is when the algorithm uses linear recursion and the algorithm only makes a recursive call as its last operation. For example, ReverseArray() uses tail recursion and LinearSum() does not
Linear Recursion • Reverse an Array by Iterative non-Recursion • Algorithm IterativeReverseArray(A, i, n): • Input: An integer array A and int i, n • Output: The reversal of n integers in A starting at index i • while n > 1 do • Swap A[i] and A[i+n-1] • i i + 1 • n n - 2 • return
Higher order recursion • When an instance of recursion algorithm makes more than a single recursive call • Algorithm BinarySum(A, i, n): • Input: An int array A and int i and n • Output: The sum of the n integers in A starting at I • if n = 1 then • return A[i] • return BinarySum(A, i, [n/2]) + • BinarySum(A, i, [n/2], [n/2])
Higher order recursion • When an instance of recursion algorithm makes more than a single recursive call • Algorithm BinaryFib(k) • Input: An int k • Output: The kth Fibonacci number • if k <= 1 then • return k • else • return BinaryFib(k-1) + BinaryFib(k-2)