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 is obtained:
- directly if (base cases);
- by using the solution of one or more instances of size smaller than if .
Example (seen later): MergeSort considers a sequence already sorted if it has one element (, ); otherwise it sorts the two halves (of sizes and , both ) and merges them.
Recursion uses induction almost in the opposite direction: induction goes from base cases up (), 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 to .
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 (start) and (end); the first call on is
reverseArray(A, 0, n-1). - Termination: if the segment has length and there is nothing to do. Otherwise swap and recurse on the inner segment.
returnhas no value because 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 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 casereverseArray(A,0,4) with :
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 caseStack 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 of size :
- 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 is the sum of the costs of all nodes.
For the worst case : maximise over all instances of size 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 the recursion tree has nodes, and each invocation does operations apart from the recursive call. The reasoning holds for upper and lower bound:
reverseArray
Instance size (length of the segment). For every instance the tree has nodes (each call shortens the segment by 2; e.g. gives 3 nodes) and each costs :
For linearSum and reverseArray the analysis is immediate because all instances of size have the same tree shape and cost per node. In general this is not so.
Powers: SimplePower vs Power
Problem: given and integer , compute . Size: .
SimplePower: .
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 nodes (a chain down to SimplePower(x,0)), each : .
Power: halve the exponent. If is even, . If is odd, . Base case (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 · yComplexity, for : at the -th recursive call the exponent is . The recursion stops at the base case after about calls, so the tree (a chain) has nodes. Each invocation does operations excluding the recursive call. Hence
This is far better than for SimplePower: takes about operations (up to constants).
Application: Fibonacci with Power
Algorithm PowerFib(n)
Input: integer n ≥ 1
Output: F_n
Φ ← ((1 + √5)/2);
Φ̂ ← ((1 - √5)/2);
return (Power(Φ, n) - Power(Φ̂, n)) / √5It performs a constant number of operations plus two calls to Power, each : . Other ways to compute Fibonacci:
- recursive algorithm directly from the definition: ;
- iterative, keeping the two previous values : .
Correctness of recursive algorithms
Correctness (like any property) of a recursive algorithm is proved by induction on the instance size :
- prove it for the base cases ;
- assuming solves correctly all instances of size for some , prove it solves instances of size .
linearSum, (, ):
- Base: returns , the sum of the one element. OK.
- Step: fix , hypothesis: linearSum is correct for every and . For an array with at least elements:
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
- Recursive algorithm: solves size directly for base cases , otherwise from solutions of smaller instances. Always give an explicit base case (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: base returns , else linearSum. reverseArray: if swap and recurse on ; first call ; in place. Both linear recursion.
- Recursion tree: node = invocation, root = first call, children = calls made directly, leaves = base cases (textbook: recursion trace).
- Execution: each call pushes an activation record on the stack (local variables, object references, LIFO, top = active call); objects live in the heap. ARs on the stack = a path of the recursion tree.
- Recursive vs iterative: iterative = non-recursive, uses loops; a recursive algorithm may have loops (MergeSort) or not.
- Complexity: cost of a node = operations excluding recursive calls; total = sum over all nodes. Upper bound: maximise over instances; lower bound: one instance or valid for all.
- linearSum: nodes, each, so .
- reverseArray (): nodes, so .
- SimplePower (): nodes, .
- Power: (even), (odd); exponent , so nodes and .
- PowerFib (, two Power calls): . Fibonacci by definition: ; iterative with two previous values: .
- Correctness: induction on size. Base cases, then assume correct for all sizes and prove . linearSum: .
- Typical mistakes: no base case; discarding the value returned by the recursive call; recursive call not matching the signature; not stating the initial call; assuming all instances of a size have the same tree (not true in general).
- 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 → and 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 →.