Download presentation
Presentation is loading. Please wait.
1
Recursion Think ESCHER
2
Recurrence Relation A rule which defines a sequence value in terms of one or more earlier values Example S(1) = 2 S(n) = 2 * S(n-1) for n >= 2 What are the values which follow 2 in the sequence?
3
Some Practise Examples
The sequence T is defined recursively as follows T(1) = 1 T(n) = T(n-1) + 3 for n>=2 What are the first 7 values in the sequence T?
4
A famous sequence The Fibonacci sequence of numbers was introduced in the 13th century by an Italian merchant and mathematician. F(1) = 1 F(2) = 1 F(n) = F(n-2) + F(n-1) for n >2 What are the first 8 numbers in the sequence
5
Recursion Definitions
Recursion is a computation using a recurrence relation A function is recursive (or “uses recursion” ) if it calls itself.
6
Bernstein nerd humor There are two kinds of people in the world, those who divide the world into two kinds of people and those who do not.
8
The following recursive definition defines a “line-drawing tree”:
Trees The following recursive definition defines a “line-drawing tree”: A line-drawing tree of complexity 1 is a single line segment 20 pixels long (the trunk). A line-drawing tree of complexity n > 1 is a line segment 20n pixels long (the trunk), with two line-drawing trees of complexity n-1 branching at 45 degree angles from its end. For example, here, from left to right, are line-drawing trees of complexities 1, 2, and 3:
9
Defining a function recursively
A function is defined recursively if the value of f(0) is given and the value of f(n+1) is given in terms of f(n). Example f(0) = 1 f(n+1) = f(n) * f(n+1) What does that function produce?
10
Programming recursion
A method calls itself directly or indirectly (to be explained later). Here’s our function f(0) = 1 f(n) = n * f(n-1) for n >0 What would the method look like? What are the first 10 values?
11
Factorial Method int factorial (int n) { int value; if (n == 0)
return value; } else { value = n * factorial (n-1);
12
What Happens in Recursion?
When a method is called, an activation record (or invocation record) is created. Method calls/returns happened in a last-in-first-out manner Activation records contain Local variables and their values The location in the caller of the method call State of the current method Other things
13
Algorithm for Selection Sort
SelectionSort (list L; integer j) // recursively sorts the items from 1 to j in list L into increasing order. if j = 1 then sort is complete, write out the sorted list else find the index i of the maximum item in L between 1 and j exchange L[i] and L[j] SelectionSort(L, j -1) end if end function SelectionSort
14
Recursive Binary Search
????
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.