Salta al contenuto
Note per Studenti Recursion and its Analysis Report

Recursion and its Analysis

In questa pagina 5

A recursive algorithm invokes itself on smaller and smaller instances until one or more base cases are reached. The solution of an instance of size nn is obtained:

  • directly if n=n0,n0+1,…,n0+kn = n_0, n_0+1, \dots, n_0+k (base cases);
  • by using the solution of one or more instances of size smaller than nn if n>n0+kn > n_0 + k.

Example (seen later): MergeSort considers a sequence already sorted if it has one element (n0=1n_0 = 1, k=0k = 0); otherwise it sorts the two halves (of sizes ⌊n/2⌋\lfloor n/2 \rfloor and ⌈n/2⌉\lceil n/2 \rceil, both <n< n) and merges them.

Recursion uses induction almost in the opposite direction: induction goes from base cases up (n→n+1n \to n+1), recursion starts from a large instance and reduces it to smaller ones down to the base case. Writing rules for recursive pseudocode (matching signature, assigning returned values, base case) are in PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode →.

Examples

linearSum: sum of the elements of an array.

Algorithm linearSum(A, n)
Input: array A of n integers, n ≥ 1
Output: sum_{i=0..n-1} A[i]
if (n = 1) then return A[0];
else return linearSum(A, n-1) + A[n-1];

It can also be written with a for loop accumulating a running sum from 00 to n−1n-1.

reverseArray: reverse the elements of an array in place (code reconstructed from the slide description).

Algorithm reverseArray(A, i, j)
Input: array A, indices i, j (the segment A[i..j] is to be reversed)
Output: A with the elements of A[i..j] in reverse order
if i < j then {
    swap A[i] and A[j];
    reverseArray(A, i+1, j-1);
}
return
  • Needs the segment bounds ii (start) and jj (end); the first call on A[0..n−1]A[0..n-1] is reverseArray(A, 0, n-1).
  • Termination: if i≥ji \ge j the segment has length ≤1\le 1 and there is nothing to do. Otherwise swap and recurse on the inner segment.
  • return has no value because AA is modified directly (in place).

Both are linear recursion: each invocation makes one recursive call.

Execution of a recursive algorithm

Recursion tree

The execution on a given instance is associated with a recursion tree (the textbook calls it recursion trace):

  • each node is a distinct recursive invocation;
  • the root is the first invocation, and the children of a node are the invocations made directly by it;
  • the leaves are the base cases.

linearSum(A,5) with A=[4,3,6,2,8]A = [4,3,6,2,8] (a chain of 5 nodes):

linearSum([4,3,6,2,8], 5)      <- root
  linearSum([4,3,6,2], 4)
    linearSum([4,3,6], 3)
      linearSum([4,3], 2)
        linearSum([4], 1)      <- base case

reverseArray(A,0,4) with A=[a,b,c,d,e]A = [a,b,c,d,e]:

reverseArray(A,0,4)   A = [a,b,c,d,e] -> swap -> [e,b,c,d,a]   <- root
  reverseArray(A,1,3)                  swap -> [e,d,c,b,a]
    reverseArray(A,2,2)                i = j: return           <- base case

Stack and heap

During execution of a program (e.g. in Java) two memory areas are involved:

  • Stack: stores the local variables of methods and references to objects. Each method invocation pushes an activation record (AR) with the local variables and references of that invocation; the AR is removed when the method ends. ARs are managed in LIFO order: only the data of the most recently pushed AR is accessible.
  • Heap: memory for dynamically created objects. ARs hold references (pointers) to objects in the heap; the heap is an unstructured area.

In a recursive algorithm the ARs on the stack correspond to the active calls, i.e. to a root-to-node path of the recursion tree. Example: while executing linearSum(A,3) called by linearSum(A,4), called by linearSum(A,5), the stack holds three ARs and the active one (on top) is linearSum(A,3).

Recursive vs iterative

  • Recursive algorithm: invokes itself on smaller instances.
  • Iterative algorithm: non-recursive. The name stresses that, except for trivial cases, a non-recursive algorithm needs loops to handle instances of arbitrary size.
  • Loops are essential in an iterative algorithm; a recursive one may or may not contain loops. linearSum and reverseArray have none, MergeSort combines recursion with iteration.

Complexity of recursive algorithms

Use the recursion tree for an instance ii of size nn:

  • assign to each node a cost = number of operations performed by that invocation excluding those of its recursive calls;
  • the total number of operations on ii is the sum of the costs of all nodes.

For the worst case tA(n)t_A(n): maximise over all instances of size nn to get an upper bound valid for every instance; for a lower bound, either exhibit one instance (one recursion tree) or build a general estimate valid for all. See Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →.

linearSum

For every instance of size nn the recursion tree has nn nodes, and each invocation does Θ(1)\Theta(1) operations apart from the recursive call. The reasoning holds for upper and lower bound:

tlinearSum(n)∈Θ(n)t_{\text{linearSum}}(n) \in \Theta(n)

reverseArray

Instance size n=j−i+1n = j - i + 1 (length of the segment). For every instance the tree has ⌊n/2⌋+1\lfloor n/2 \rfloor + 1 nodes (each call shortens the segment by 2; e.g. n=5n = 5 gives 3 nodes) and each costs Θ(1)\Theta(1):

treverseArray(n)∈Θ(n)t_{\text{reverseArray}}(n) \in \Theta(n)

For linearSum and reverseArray the analysis is immediate because all instances of size nn have the same tree shape and cost per node. In general this is not so.

Powers: SimplePower vs Power

Problem: given x∈Rx \in \mathbb{R} and integer n≥0n \ge 0, compute xnx^n. Size: nn.

SimplePower: xn=x⋅xn−1x^n = x \cdot x^{n-1}.

Algorithm SimplePower(x, n)
Input: x ∈ R and integer n ≥ 0
Output: x^n
if (n = 0) then return 1;
else return x · SimplePower(x, n-1)

The tree has n+1n+1 nodes (a chain down to SimplePower(x,0)), each Θ(1)\Theta(1): tSimplePower(n)∈Θ(n)t_{\text{SimplePower}}(n) \in \Theta(n).

Power: halve the exponent. If n>0n > 0 is even, xn=(xn/2)2x^n = (x^{n/2})^2. If n>0n > 0 is odd, xn=x⋅xn−1=x⋅(x(n−1)/2)2x^n = x \cdot x^{n-1} = x \cdot (x^{(n-1)/2})^2. Base case n=0n = 0 (a recurrence relation: the value is defined through previous values).

Algorithm Power(x, n)
Input: x ∈ R and integer n ≥ 0
Output: x^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

Complexity, for n>1n > 1: at the ii-th recursive call the exponent is ni≤n/2in_i \le n/2^i. The recursion stops at the base case after about log⁡2n\log_2 n calls, so the tree (a chain) has O(log⁡n)O(\log n) nodes. Each invocation does Θ(1)\Theta(1) operations excluding the recursive call. Hence

tPower(n)∈O(log⁡n)t_{\text{Power}}(n) \in O(\log n)

This is far better than Θ(n)\Theta(n) for SimplePower: xnx^n takes about log⁡n\log n operations (up to constants).

Application: Fibonacci with Power

From Fn=15(Φn−Φ^n)F_n = \dfrac{1}{\sqrt5}(\Phi^n - \hat\Phi^n) (proved by induction in Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants →):

Algorithm PowerFib(n)
Input: integer n ≥ 1
Output: F_n
Φ ← ((1 + √5)/2);
Φ̂ ← ((1 - √5)/2);
return (Power(Φ, n) - Power(Φ̂, n)) / √5

It performs a constant number of operations plus two calls to Power, each O(log⁡n)O(\log n): tPowerFib(n)∈O(log⁡n)t_{\text{PowerFib}}(n) \in O(\log n). Other ways to compute Fibonacci:

  • recursive algorithm directly from the definition: Ω(2n)\Omega(2^n);
  • iterative, keeping the two previous values Fi−1,Fi−2F_{i-1}, F_{i-2}: Θ(n)\Theta(n).

Correctness of recursive algorithms

Correctness (like any property) of a recursive algorithm is proved by induction on the instance size nn:

  • prove it for the base cases n∈[n0,n0+k]n \in [n_0, n_0+k];
  • assuming AA solves correctly all instances of size m∈[n0,n]m \in [n_0, n] for some n≥n0+kn \ge n_0 + k, prove it solves instances of size n+1n+1.

linearSum, n≥1n \ge 1 (k=0k = 0, n0=1n_0 = 1):

  • Base: n=1n = 1 returns A[0]A[0], the sum of the one element. OK.
  • Step: fix n≥1n \ge 1, hypothesis: linearSum(A,m)(A, m) is correct for every AA and 1≤m≤n1 \le m \le n. For an array with at least n+1n+1 elements:

linearSum(A,n+1)=linearSum(A,n)+A[n]=∑i=0n−1A[i]+A[n]=∑i=0nA[i]\text{linearSum}(A, n+1) = \text{linearSum}(A, n) + A[n] = \sum_{i=0}^{n-1} A[i] + A[n] = \sum_{i=0}^{n} A[i]

An iterative version (with a support variable sum) can be proved with an invariant instead (Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants →).

Exercises on the slides: test the correctness of reverseArray and Power; design a recursive element-uniqueness algorithm (all elements of an array distinct?) without sorting and analyse it with the recursion tree.

Versione ripasso

Teoria collegata